好的,我正在为单链表创建一个 ADT。我有一个结构名称列表,它存储指向第一个节点的指针(列表中的第一项,它也是一个结构)和大小。该节点存储名字和指向下一个节点的指针。以下是结构:
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 和一个新节点,我将 list->head 分配给新节点的地址;
newList->head = newNode;
直到这一次编译器没有提示。但是当我尝试使用列表中的指针访问第一个节点中的元素时:
name = newList->head->name;
编译器提示 struct List 没有名为“name”的成员
我如何访问结构节点中的字段,假设我只有指向结构列表的指针,并且 List->head 指向第一个节点。 任何帮助将不胜感激。
最佳答案
假设 NodeP 是一个节点*,当它应该是 NodeP
类型时,您将 head 声明为 ListP
。
尝试与名字保持一致。这是建议的修订:
// 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;
};
关于c - C中链表的两个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26197482/