2016-04-22 51 views
0

我的鏈表中每個節點的值現在都等於'temp',儘管我希望它們保持獨立。在while(1)循環的最後一次迭代中,當'temp'被分配給「STOP」時,所有其他值也被打印爲「STOP」。如何將結構的char []賦值爲文件的值,而不是指針?

//******************* 
//* 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; 
} 

回答

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); 

二,保留結構不變,而是使臨時的新副本:

// trace->payload->name = temp; do not assign here, copy the string 
trace->payload->name = strdup(temp); 
+0

啊, 謝謝!這工作! –