【发布时间】:2014-11-29 14:32:46
【问题描述】:
好的,我正在为单链表创建 ADT。我有一个结构名称列表,它存储指向第一个节点的指针(列表中的第一项,也是一个结构)和大小。该节点存储名字和指向下一个节点的指针。以下是结构:
typedef struct List *ListP;
struct List{
ListP head;
int size;
};
struct node{
char name[20];
nodeP next;
};
首先我调用 malloc 来给我 struct List 的内存:
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 和一个新节点,我将 list->head 分配给新节点的地址;
newList->head = newNode;
直到这个时候编译器没有抱怨。但是当我尝试使用列表中的指针访问第一个节点中的元素时:
name = newList->head->name;
编译器抱怨 struct List 没有名为 'name' 的成员
我如何访问结构节点中的字段,假设我只有指向结构列表的指针,而 List->head 指向第一个节点。 任何帮助将不胜感激。
【问题讨论】:
-
typedef struct node *nodeP;..ListP head;-->nodeP head;
标签: c struct malloc singly-linked-list