2012-12-22 112 views
0

我很困惑!尝试创建动态链接列表并希望通过“malloc”函数分配标题。从我的下面编译代码给出2错误:“节点”的奇怪行为

在主 [错误] node' undeclared (first use in this function) and **In function newnode ':** [错误]`节点' 未声明(第一在此函数使用)

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

struct node{ 
    int a,b,c,d; 
    struct node *next; 
}; 

struct node * newnode(int, int, int, int); 

int main(){ 
    struct node *header; 
    header=(struct node *)malloc(sizeof(node)); 
    int a,b,c,d; 
    a=11; 
    b=2; 
    c=4; 
    d=5; 
    header->next=newnode(a,b,c,d); 
    printf("\n\n"); 
    system("PAUSE"); 
    return 0; 
} 

struct node * newnode(int aa, int bb, int cc, int dd) 
{ 
    struct node *temp; 
    temp=(struct node*)malloc(sizeof(node)); 
    temp->a =aa; 
    temp->b =bb; 
    temp->c =cc; 
    temp->d =dd; 
    temp->next=NULL; 
    return temp; 
} 

我欣赏任何建议!谢谢!

回答

2

没有类型node。你有类型struct node,这是你需要传递给sizeof运营商的那个。

+0

是BRO!谢谢! –

1

首先,正如@icepack已经提到的那样,该类型被命名为struct node,而不是node。所以,sizeof(node)不能编译。您在代码中随处使用struct node,除了在sizeof这两处。

其次,可以考虑使用

T *p = malloc(n * sizeof *p); /* to allocate an array of n elements */ 

成语内存分配。例如。在你的情况下

temp = malloc(sizeof *temp); 

即,不要将malloc的结果和sizeof的表达式结合使用,而不要输入类型名称。类型名称属于声明。其余代码应尽可能与类型无关。

1

正如前面的答案所述,在引用结构时必须使用struct node

不过,如果你只是想使用声明名称节点,你可以做如下:

typedef struct _node{ 
    int a,b,c,d; 
    struct _node *next; 
} node; 

在这里你不需要使用struct您引用node

编辑前:错误的语法

+0

这只是错误的语法 –

+0

@JensGustedt修复了它 –