我已經閱讀了很多有關存儲器分配指向數組的指針理論問題的答案,但尚未能修復我的代碼......所以轉向了您。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