2012-12-22 110 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修復了它 –