當我在兩個函數之間傳遞一個變量時,我遇到了一些問題。通過函數之間的指針
我有這樣的結構:
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;
}
}
的問題是,在打印()站點變量正在循環,但不是時間變量。我想不通爲什麼...
這裏是我的功能還呼籲:
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;
}
我想從文本文件網絡中的每一行構造一個鏈表,然後構造一個函數將其打印出來。我感覺在所有這些指針/無指針決策中都迷失了... – theva
這很難概括,但是當您使用可變大小的數據(如字符串)或可變數量的記錄時(如在鏈接中)時,通常需要指針列表)。在「line」中,您可以將station更改爲「char station [40]」,因爲您在readFile()中已經有固定的大小限制。 「line :: time」可能應該只是「int time」。 – joeking