2014-10-04 41 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