2016-11-13 37 views
-2

目前我正在试图填补一个结构类似这样的的C指针运算,以填补结构

typedef struct 
{ 
    int year; 
    int month; 
    int day; 
    int hour; 
    int minute; 
} tDateTime; 

typedef struct sFlight 
{ 
    char code[MAX_NAME_LENGTH]; 
    char arrival[MAX_NAME_LENGTH]; 
    char departure[MAX_NAME_LENGTH]; 
    int availableSeats; 
    tDateTime dateTime; 
    struct sFlight * nextFlight; 
} tFlight; 

从一个txt文件中读取。这是我目前正在做的

void ops_loadFlightsInformation(tFlight * firstFlight) 
{ 
    // Open the file with r to only read 
    FILE *file = fopen(OPS_FLIGHTS_FILE, "r"); 
    // If file is not open return 
    if(file == NULL) { 
     return; 
    } 

    tFlight currentFlight; 

    // Loop until there are no flights 
    while(next != 0) { 
     strcpy(currentFlight.code, helpers_scanFromFile(file, MAX_NAME_LENGTH)); 
     strcpy(currentFlight.departure, helpers_scanFromFile(file, MAX_NAME_LENGTH)); 
     strcpy(currentFlight.arrival, helpers_scanFromFile(file, MAX_NAME_LENGTH)); 
     fscanf(file, "%d\n", &currentFlight.availableSeats); 
     fscanf(file, "%d/%02d/%02d %02d:%02d\n", &currentFlight.dateTime.year, &currentFlight.dateTime.month, &currentFlight.dateTime.day, &currentFlight.dateTime.hour, &currentFlight.dateTime.minute); 
     fscanf(file, "%d\n", &next); 

     printf("%s \n", currentFlight.code); 
    } 

    printf("%s \n", firstFlight->code); 

    // Close the file handle 
    fclose(file); 
} 

我不能设法思考如何填充while循环的结构指针。我尝试了不同的方式,但我总是以

warning: X may be used uninitialized in this function 

或者只是一遍又一遍地编辑相同的指针,所以只编辑第一个元素。循环工作正常currentFlight得到正确填充,但我不知道如何将其翻译到firstFlight结构和 - > nextFlight指针

+0

代码中没有变量X;实际的信息和行号以及变量是什么。 –

+0

你有一个设计问题。您的功能可能会失败,但呼叫代码无法知道它失败。那很糟。 –

回答

1

你想读取航班,并把它们放在一个列表中。因此,在阅读下一个航班之前,分配一块新的内存并将其放入next。然后使用指针符号,以解决成员:

void ops_loadFlightsInformation(tFlight * firstFlight) 
{ 
    // Open the file with r to only read 
    FILE *file = fopen(OPS_FLIGHTS_FILE, "r"); 
    // If file is not open return 
    if(file == NULL) { 
     return; 
    } 

    tFlight *currentFlight = firstFlight; 

    // Loop until there are no flights 
    while(!feof(file)) { 
     currentFlight->next= malloc(sizeof(tFlight)); 
     currentFlight= currentFlight->next; 
     strcpy(currentFlight->code, helpers_scanFromFile(file, MAX_NAME_LENGTH)); 
     strcpy(currentFlight->departure, helpers_scanFromFile(file, MAX_NAME_LENGTH)); 
     strcpy(currentFlight->arrival, helpers_scanFromFile(file, MAX_NAME_LENGTH)); 
     fscanf(file, "%d\n", &currentFlight->availableSeats); 
     fscanf(file, "%d/%02d/%02d %02d:%02d\n", &currentFlight->dateTime.year, &currentFlight->dateTime.month, &currentFlight->dateTime.day, &currentFlight->dateTime.hour, &currentFlight->dateTime.minute); 
     //fscanf(file, "%d\n", &next); // what is this????? 

     printf("%s \n", currentFlight->code); 
    } 

    printf("%s \n", firstFlight->code); 

    // Close the file handle 
    fclose(file); 
} 

(注:上scanf校验码和malloc应添加假设你的助手是正确的,总是读字符串假定该文件包含至少一个航班。)