当我在两个函数之间传递一个变量时,我遇到了一些问题。
我有一个这样的结构:
typedef struct line{
char *station;
int *time;
struct line *next;
} *Line;
然后是第一个函数:
void readFile(FILE *network, Line *list){
int line;
char station[40];
char next[40];
int time;
char buffer[128];
while(fgets(buffer, 128, network)){
Line newNode = malloc(sizeof(struct line));
sscanf(buffer, "%d, %50[0-9a-zA-Z ], %50[0-9a-zA-Z ], %d", &line, station, next, &time);
newNode->station = malloc(strlen(buffer) + 1);
strcpy(newNode->station, station);
newNode->time = malloc(strlen(buffer) + 1);
newNode->time = &time;
newNode->next = *list;
*list = newNode;
printf("%s %d\n",newNode->station, *newNode->time); // This one print each newNode->time correctly...
}
}
第二个功能:
void print(Line cursor){
while(cursor != NULL){
printf("Station: %s ",cursor->station);
printf("Tid: %d\n",*cursor->time);
cursor = cursor->next;
}
}
问题是在 print() 中,站变量正确循环,而不是时间变量。我想不通为什么...
这也是我的函数调用:
int main(){
FILE *network = fopen("network.txt", "r"); // Open file for reading
Line list = NULL;
readFile(network,&list);
printf("%s %d\n",list->next->next->next->station, *list->next->next->next->time);
print(list);
return 0;
}