好吧我正在创建一个单链表的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的指针指向第一个节点。 任何帮助,将不胜感激。
'typedef结构节点*节点p;''..头ListP;' - >'节点p头;' – BLUEPIXY 2014-10-04 21:47:37
[在C,你应该不投malloc'的'结果] (http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 – 2014-10-04 22:02:09