错误:未声明(首次使用此功能)

时间:2015-12-20 08:52:58

标签: c struct

我用C语言编码,无法找出错误。它一直告诉我 第一: 在这一行

temp = (Node*) malloc(sizeof(struct Node));

Node未声明,首次使用是在此函数中。但我想我之前已经宣布过。

第二: 在同一行

  

“'之前的预期表达'''令牌”

指向(Node*)

和第三:

  

“输入结束时的预期声明或声明。”

虽然它指向已关闭的}主。

对于第一个我搜索并发现它是因为C89而且我必须在我的函数顶部声明所有变量。我做了但是错误仍然存​​在。

这是我的代码:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h> 
#include <malloc.h>

 struct Node{
    int data;
    struct Node* next;
};

struct Node* head;

void Add(int x){
    struct Node* temp;
    temp = (Node*) malloc(sizeof(struct Node));
    temp -> data = x;
    temp -> next = head;
    head = temp;
}

void print(){
    struct Node* temp;
    temp = head;
    printf("List is:");
    while(temp != NULL){
        printf(" %s",temp -> data);
        temp = temp -> next;
    }
int main(int argc, char **argv)
{

    head = NULL;
    Add(3);
    print();
    return 0;
}

我正在尝试使用链接列表。

1 个答案:

答案 0 :(得分:6)

在您的代码中

 temp = (Node*) malloc(sizeof(struct Node));

应该是

 temp = malloc(sizeof(struct Node));

或者,为了更好,

 temp = malloc(sizeof *temp);

消除此问题,正如您need not to cast the return value of malloc() and family in C.

但错误是因为您错过了那里的struct关键字。

要解决第三个错误,

  

“输入结束时的预期声明或声明。”

好吧,你错过了}函数的结尾print()

FWIW,在使用它之前,你应该始终通过malloc()和函数族来检查返回指针的有效性。

话虽如此,

  

对于第一个我搜索并发现它是因为C89而我必须在函数顶部声明所有变量

不是真的。是的,在C89中,您需要在顶部声明所有变量,但这无法让您跳过 struct关键字。

相关问题