【问题标题】:Two structs for a linked list in CC中链表的两个结构
【发布时间】: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 指向第一个节点。 任何帮助将不胜感激。

【问题讨论】:

标签: c struct malloc singly-linked-list


【解决方案1】:

假设 NodeP 是一个节点*,您将 head 声明为 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;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 2021-05-11
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多