2014-10-04 43 views
0

好吧我正在創建一個單鏈表的ADT。我有一個結構名稱列表,存儲指向第一個節點(列表中的第一個項目,也是一個結構)和大小的指針。節點存儲名字和指向下一個節點的指針。下面是sturcts:在C中的鏈表的兩個結構體

typedef struct List *ListP; 

struct List{ 
    ListP head; 
    int size; 
    }; 

struct node{ 
    char name[20]; 
    nodeP next; 
    }; 

首先,我叫的malloc給我的結構列表存儲:

ListP newList; 
    newList = malloc(sizeof(struct List)); //should I typecast this to (ListP *)? 
    if (newList == NULL){ 
     fprintf(stderr, "Memory allocation failed"); 
    } 
    else{ 
     newList->head = NULL;  
     newList->size = 0;  
    } 

然後我打電話的malloc再次給我的內存爲第一個節點:

struct node *new; 
    newNode = malloc(sizeof(struct node)); 
    if (newNode == NULL){ 
     fprintf(stderr, "Memory allocation failed"); 
    } 
    else{ 
     newNode->name = 'Jay'; 
     newNode->next = NULL; 

既然我有我的列表和一個新節點,我將list-> head分配給新節點的地址;

newList-> head = newNode;

直到這次編譯器沒有抱怨。但是,當我嘗試使用我的列表中的指針來訪問的第一個節點的元素:

name = newList->head->name; 

編譯器抱怨結構列表沒有名爲「名」

如何訪問成員在struct node中的字段,假設我只有指向struct List和List-> head的指針指向第一個節點。 任何幫助,將不勝感激。

+0

'typedef結構節點*節點p;''..頭ListP;' - >'節點p頭;' – BLUEPIXY 2014-10-04 21:47:37

+0

[在C,你應該不投malloc'的'結果] (http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 – 2014-10-04 22:02:09

回答

2

假設NodeP是一個節點*,您應將其聲明爲ListP,並且該類型應爲NodeP

嘗試與名稱一致。這裏有一個建議修訂:

// forward declarations 
struct List; 
struct Node; 

typedef struct List *ListP; 
typedef struct Node *NodeP; 

struct Node{ 
    char name[20]; 
    NodeP next; 
}; 

struct List{ 
    NodeP head; 
    int size; 
}; 
+0

謝謝,我會嘗試 – pdhimal1 2014-10-04 21:49:42