我链接列表中每个节点的值现在都等于'temp',尽管我希望它们保持独立。当'temp'在while(1)循环的最后一次迭代中被分配给“STOP”时,所有其他值也被打印为“STOP”。
//*******************
//* GEORGE TANGEN *
//* HW 9 *
//*******************
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node{
struct node *next;
struct building *payload;
};
struct building{
char *name;
struct arc *list[];
};
struct arc{
int weight;
struct building *start;
struct building *end;
};
int main(){
struct node *head;
struct node *trace;
head = malloc( sizeof(struct node) );
head->payload = malloc( sizeof(struct building) );
head->payload->name = "Head";
int k;
trace = head;
for(k=0;k<10;k++){
trace->next = malloc( sizeof(struct node) );
trace = trace->next;
trace->payload = malloc( sizeof(struct building) );
trace->payload->name = "hi";
}
FILE *f1;
int i,j;
char *op = {"hw9.data"};
f1 = fopen(op,"r");
if(f1==NULL){
printf("No File!");
return 0;
}
trace = head;
char temp[200];
while(1){
fscanf(f1, "%s", temp);
if( (strcmp(temp, "STOP"))==0 ){
break;
}else{
printf("INPUT: %s\n", temp);
trace->payload->name = temp;
printf("OUTPUT: %s\n", trace->payload->name);
printf("HEAD: %s\n", head->payload->name);
trace = trace->next;
}
printf("%s\n\n", temp);
}
trace = head;
for(k = 0; k<10;k++){
printf("OUTPUT: %s\n", trace->payload->name);
trace = trace->next;
}
fclose(f1);
return 0;
}
答案 0 :(得分:2)
每次在其上调用temp
时,都会覆盖数组fscanf
的内容,有两种方法。
首先,定义有效负载以保存字符数组,而不仅仅是指针
struct node{
struct node *next;
struct building *payload;
};
struct building{
char name[256];
struct arc *list[];
};
// trace->payload->name = temp; do not assign here, copy the string
strcpy(trace->payload->name, temp);
其次,保持struct不变,而是创建temp的新副本:
// trace->payload->name = temp; do not assign here, copy the string
trace->payload->name = strdup(temp);