【问题标题】:Getting an error message saying the variable has not been declared when it has收到一条错误消息,说明变量尚未声明
【发布时间】:2014-04-01 15:36:46
【问题描述】:

这是我的代码:

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

我收到的错误消息是“carReg”尚未声明,“make”尚未声明等。

有人可以帮忙吗?

编辑 - 我更新了它,它全部编译但程序没有运行。它运行但显示 title.exe 已停止运行。

【问题讨论】:

  • 你需要 -> 而不是 . 的所有指针,而不仅仅是其中一些指针
  • newCar 不应该是一个指针。目前您的代码没有保存aNodeanElement 中的任何指针。
  • @ooga 我在上面编辑了我的评论。它可以编译但不能正常运行。
  • 每个问题一个问题。这就是 Stackoverflow 的规则。您应该提出一个新问题,而不是编辑您的问题。

标签: c struct declaration


【解决方案1】:

struct data *anElement, *newCar; 替换为struct data *anElement; struct data newCar;

目前fread()sizeof(struct data) 字节读入指针(&newCar 是指针的地址),这可能不是您想要的(这也是典型的缓冲区溢出)。

这也将解决您遇到的错误,因为您尝试使用 . 运算符通过指针访问结构成员。更改 newCar 定义将解决此问题。

【讨论】:

  • jf95,如果答案解决了您的问题,您应该接受它作为解决方案。
猜你喜欢
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
  • 1970-01-01
相关资源
最近更新 更多