2017-04-14 79 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