2017-04-14 70 views
-2

我已经阅读了很多有关存储器分配指向数组的指针理论问题的答案,但尚未能修复我的代码......所以转向了您。C指针字符串数组指针稍后被复制时出现乱码

我有一个STRUCT中的字符串数组,我需要写入和读取。声明为:

typedef struct client_mod 
{  
/* Client ad_file */ 
char *ad_filenames[10]; 
/* Client's current ad array index*/ 
unsigned int ad_index; 

} client; 

然后,在函数内部,我将值分配给指针:

/* in looping code block */ 

LOG("Checking file under index = %d, file is %s", client->ad_index, client->ad_filenames[client->ad_index]); 

前两个部件:

static int get_spots (client_mod *client) 
{ 

char buf[512]; 
FILE *ptr; 

if ((ptr = popen("php /media/cdn/getspot.php", "r")) != NULL) { 
/* Read one byte at a time, up to BUFSIZ - 1 bytes, the last byte will be used for null termination. */ 
size_t byte_count = fread(buf, 1, 512 - 1, ptr); 
/* Apply null termination so that the read bytes can be treated as a string. */ 
buf[byte_count] = 0; 
} 

(void) pclose(ptr); 

// parse extracted string here... 
int i = 0; 
client->ad_filenames[i] = strdup(strtok(buf,"|")); 

while(client->ad_filenames[i]!= NULL && i<5) 
    { 
    client->ad_filenames[++i] = strdup(strtok(NULL,"|")); 
    if (client->ad_filenames[i] != NULL && strlen(client->ad_filenames[i]) > 5) { 
    LOG("TESTING FOR CORRECT FILE NAMES %s\n", client->ad_filenames[i]); 
    } 
} 

} 

当我retreive的值以后,问题就来阵列正常恢复,之后的所有内容都是乱码。 我将不胜感激任何指导。谢谢! 我明白这个probablby来自直接分配给指针的未定义行为,但我无法弄清楚如何解决它。

+0

我们需要看到更多的代码。为什么你需要一个10个指针的数组?你分配这些指针的值来自哪里? –

+1

'var1'可能被声明为'char var1 [some_size]',是吗?如果是这样,你应该阅读范围和自动存储时间。 –

+0

什么类型是'var1'?如果它是一个指向已将字符串数据复制到的malloced数组的指针,则罚款,否则.... – ThingyWotsit

回答

0

我认为问题是分配给这个struct元素。

char *ad_filenames[10]; 

ad_filenames是指针10的阵列,以字符。

这意味着每个索引需要内存分配。

类似于 client-> ad_filenames [0] = strdup(var1);

strdup()在此函数中同时执行malloc()和strcpy()。

客户端应该是一个变量名。您已经将客户定义为一种类型。

这里是工作代码:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct client_mod 
{  
    /* Client ad_file */ 
    char *ad_filenames[10]; 
    /* Client's current ad array index*/ 
    unsigned int ad_index; 

}CLIENT1; 

CLIENT1 *client; 


int func(char *var1) { 
    client->ad_filenames[0] = strdup(var1); 
} 

int 
main(void) 
{ 
    char str1[10]; 
    client = malloc(sizeof client); 

    strcpy(str1, "Hello"); 
    func(str1); 

    printf("%s\n", client->ad_filenames[0]); 

    free(client->ad_filenames[0]); 
    free (client); 

} 
+0

谢谢 - 现在就测试并尽快报告。 – user2280389

+0

你只使用ad_filenames [0],没有索引。在代码中注意,client-> ad_filenames [i] = strdup(strtok(buf,“|”)); – ChuckCottrill

+0

这只是关于strdup()的用法的一个例子。这并不是一个完整的代码。 –

0

你的问题是与行,

size_t byte_count = fread(buf, 1, 1000 - 1, ptr); 

阅读手册FREAD页,

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); 

你读1000-1成员大小1到buf,这是只分配buf [512],要么扩大buf或减少fread第3个参数,

buf[1000+1]; 
size_t byte_count = fread(buf, 1, sizeof(buf)-1, ptr); 
+0

谢谢 - 在这里移动代码时这是一个错字;根本问题是Nguai-al指出的一个问题。 – user2280389

+0

你提供的代码片段有strdup。而且你还键入了一个类型'client',但是用它作为指针参数的名字。 – ChuckCottrill