2012-07-21 82 views
3
#include <stdio.h> 
typedef int element_type; 

typedef struct Cell{ 
    element_type e; 
    struct Cell *next; 
} Cell,*List; 

Cell *End(List L){ 
    Cell *q = L; 
    while (q->next != NULL){ 
    q = q->next; 
    } 
    return q; 
} 

void Insert(Cell *p, element_type x){ 
    //Create new Cell 
    Cell *temp = (Cell*) malloc(sizeof(Cell)); 
    if (temp == NULL){ 
    printf("Memory Allocation Failed");  
    } 
    else{ 
    temp->e = x; 
    temp->next = p->next; 
    p->next = temp; 
    } 
} 

element_type Retrieve(Cell *p){ 
    return p->e; 
} 
int main(){ 
    //Initialize the List; 
    List L = malloc(sizeof(Cell)); 
    L->e = NULL; 
    L->next = NULL; 

    element_type x = 10; 
    Insert(L,x); 
    printf("Just retrievd the item %d\n",Retrieve(L)); 
    return 1; 
} 

List_pointer.c: In function ‘Insert’: 
List_pointer.c:19:24: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default] 
List_pointer.c: In function ‘main’: 
List_pointer.c:35:12: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default] 
List_pointer.c:36:8: warning: assignment makes integer from pointer without a cast [enabled by default] 

感謝您的所有幫助,我現在與結構部分。但是,當我嘗試使用malloc時,我再次收到了有關不兼容聲明的警告。我以爲malloc返回一個泛型指針爲NULL,因此應該不會有任何問題鑄造?我只是不確定我在這裏做錯了什麼。警告不兼容的指針,爲什麼會發生這種情況?

對於那些想知道爲什麼我會實現這樣一個奇怪的接口的人,我正在關注由Aho提供的書「數據結構和算法」提供的接口。示例代碼以Pascal的形式給出,非常古老。雖然我認爲學習這種超級老式的數據結構設計有一些優點。

更新:

我只是忘了包括在的malloc stdlib.h中頭球攻門! 請參考此鏈接incompatible implicit declaration of built-in function ‘malloc’

回答

3

你需要改變

typedef struct { 

typedef struct Cell { 

typedef struct { /* ... */ } Cell;定義了一個無代碼結構。實際上,結構本身沒有可以直接引用的名稱。名稱Cell只是引用該未命名結構的typedef的名稱。

當您使用struct Cell聲明next時,它表示「結構名爲Cell」。但是,沒有名爲Cell的結構,因爲您定義的結構沒有名稱。

通過命名結構(給它一個標記),可以使用struct Cell表示法來引用它。

2

您需要爲您提供struct標籤,不僅是一個typedef:

typedef struct Cell { 
    element_type e; 
    struct Cell *next; 
} Cell,*List; 

沒有標籤那裏,struct Cell *是不確定的,導致錯誤。

這是非常有助於瞭解這種類型定義的解剖結構:它是兩個聲明的組合:

struct Cell { 
    element_type e; 
    struct Cell *next; 
}; 

typedef struct Cell Cell; 

沒有標籤,你是typedef -ing一個無代碼struct

相關問題