所以在我的計劃有一個結構:字符指針被覆蓋的
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);
是否有某種解決方法可以讓我的結構保持不變並且正確賦值?
太謝謝你了。你是救生員。在我的程序中,哪一點會被認爲是釋放內存的最佳實踐? – Drew
完成引用後,可以隨時釋放內存。如果最後一次使用'set'在'printf'調用之後,那將是一個好地方。 – simonc