2014-04-01 56 views
0

這裏是我的代碼:收到錯誤消息說變量沒有被宣佈時,它具有

struct data { 
    char carReg[6]; 
    char make[20], model[20], colour[20]; 
    int numPrevOwners; 
    bool reserved; 
    float reserveAmount; 
}; 

struct node { 
struct data *element; 
struct node *next; 
}; 

而且在我的主要方法,我有這樣的:

struct node *current, *aNode; 
struct data *anElement, *newCar; 
FILE *file; 

file = fopen("d:car.dat", "r"); //open the file for reading 
if (file == NULL) { 
    printf("Nothing found in this file.\n\n"); 
    printf("\n"); 
}//end if 
else { 
    //If it does exist, cars in file should be copied into the linked list 
    while(fread(&newCar, sizeof(struct data), 1, file)>0) {   

     aNode = (struct node *)malloc(sizeof(struct node)); 
     anElement = (struct data *)malloc(sizeof(struct data)); 

     strcpy(anElement->carReg ,newCar->carReg); 
     strcpy(anElement->make, newCar->make); 
     strcpy(anElement->model, newCar->model); 
     strcpy(anElement->colour, newCar->colour); 
     anElement->numPrevOwners = newCar->numPrevOwners; 
     anElement->reserved = newCar->reserved; 
     anElement->reserveAmount = newCar->reserveAmount; 

     if (aNode == NULL) 
      printf("Error - no space for the new node\n"); 

      else { // add data part to the node 
       aNode->element = anElement; 
       aNode->next = NULL; 

       if (isEmpty()) 
       { 
        front = aNode; 
        last = aNode; 
        } 

        else { 
        last->next = aNode; 
        last = aNode; 
        } 

       } 
    }//end while 

    printf("Cars in the system"); 
}//end else 

錯誤消息我m得到是'carReg'尚未申報,'make'尚未申報等。

任何人都可以幫忙嗎?

編輯 - 我有它更新,它都編譯,但程序不運行。它運行但說title.exe已停止運行。

+0

你需要所有指針代替'''',而不是''',而不僅僅是其中的一些 – deviantfan

+0

'newCar'不應該是一個指針。目前你的代碼並沒有保存'aNode'或'anElement'中的任何指針。 – ooga

+0

@ooga我上面編輯了我的評論。它編譯但不能正常運行。 – jf95

回答

0

struct data *anElement, *newCar;替換爲struct data *anElement; struct data newCar;

目前fread()sizeof(struct data)字節爲指針(&newCar是一個指針的地址),這可能不是你想要的(並且也是這是一個經典的緩衝區溢出)。

這也將修復您遇到的錯誤,因爲您試圖通過使用.運算符的指針訪問結構成員。更改newCar定義將解決此問題。

+0

謝謝。它編譯正確,現在可以工作。 – jf95

+0

jf95,如果答案解決了您的問題,您應該接受它作爲解決方案。 – user1205577

相關問題