我已经阅读了很多有关存储器分配指向数组的指针理论问题的答案,但尚未能修复我的代码......所以转向了您。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来自直接分配给指针的未定义行为,但我无法弄清楚如何解决它。
我们需要看到更多的代码。为什么你需要一个10个指针的数组?你分配这些指针的值来自哪里? –
'var1'可能被声明为'char var1 [some_size]',是吗?如果是这样,你应该阅读范围和自动存储时间。 –
什么类型是'var1'?如果它是一个指向已将字符串数据复制到的malloced数组的指针,则罚款,否则.... – ThingyWotsit