2013-02-01 55 views
1

所以在我的計劃有一個結構:字符指針被覆蓋的

typedef struct Point { 
    double x, y; 
    char *label; 
} point; 

然後我從文件中讀取一些信息,並在陣列內指定不同的標籤,以不同的點結構。問題是,儘管x,y值被正確地賦值,但標籤對於內存中的每個結構都是相同的。

point set[3]; 

FILE *file = fopen(argv[1], "r"); 

int count = 0; 
char *pch; 
char line[128]; 

if(file != NULL){ 
    while(fgets (line, sizeof line, file) != NULL){ 
     pch = strtok(line, " "); 
     int i = 0; 

     while(pch != NULL){ 
      if(i==0){set[count].label = pch;} 
      if(i==1){set[count].x = atof(pch);} 
      if(i==2){set[count].y = atof(pch);} 
      pch = strtok(NULL, " "); 
      i++; 
     } 
     count++; 
    } 
    fclose(file); 
} 

//these values should not be the same, though they are 
printf("%s\n", set[0].label); 
printf("%s\n", set[1].label); 

是否有某種解決方法可以讓我的結構保持不變並且正確賦值?

回答

4

您需要爲每個標籤instance分配內存。是作爲數組

typedef struct Point { 
    double x, y; 
    char label[50]; 
} point; 

strcpy(set[count].label, pch); 

或通過爲每個label實例動態地分配存儲器

set[count].label = malloc(strlen(pch)+1); 
strcpy(label, pch); 

(在後者的情況下確保以後free(set[count].label)

+0

太謝謝你了。你是救生員。在我的程序中,哪一點會被認爲是釋放內存的最佳實踐? – Drew

+0

完成引用後,可以隨時釋放內存。如果最後一次使用'set'在'printf'調用之後,那將是一個好地方。 – simonc

0

所有指針指向相同的存儲器位置,可以通過將 的結構成員標籤更改爲

char label[100]; 

或動態分配內存就是這樣,

if(i==0){ 
    set[count].label = (char *) malloc(sizeof(char)*(strlen(pch)+1)); 
    strcpy(set[count].label,pch); 
}