如何将 Typedef 结构名称与指针一起使用

How to Use Typedef Structure Name with Pointer

我正在尝试使用给定的结构为一个更大的项目实现一个链表。结构定义如下:

typedef struct node {
   unint32_t size; // = size of the node
   struct node * link; // = .next pointer
} * ListNode;

我能够使用 struct node * 实现链表。但是当我尝试在以下程序中使用 ListNode 时:

typedef struct node {
    unint32_t size;
    struct node * link;
} * ListNode;


void insert_node (ListNode * head, unint32_t size) {
 ListNode new_node = (ListNode) malloc (sizeof(ListNode));

 new_node->size = size;
 new_node->link = NULL;

 if (head == NULL) {
  head = &new_node;
 }

 else {
  ListNode current = *head;

  while (current->link != NULL) {
   current = current->link;
  }

  current->link = new_node;
 }
}


int main (int argc, char const * argv[]) {
 ListNode head = NULL;
 insert_node (&head, 10);
 insert_node(&head, 20);

 ListNode ptr = head;

 while (ptr != NULL) {
   printf ("%d ", ptr->size);
 }
 printf ("\n");
 
 return 0;
}

我遇到了分段错误。这是为什么?它甚至说 struct node *ListNode 不兼容 pointers/types。我以为它们是一样的 struct 只是名字不同。

  • 由于您向 insert_node 提供了一个 struct node**(一个 ListNode*),因此您需要取消引用它才能分配给它。
  • malloc一个struct node*的大小(一个ListNode)但是你需要malloc一个struct node的大小。
  • 您还需要在 main 的循环中执行 ptr = ptr->link

示例:

void insert_node(ListNode* head, uint32_t size) {
    // corrected malloc, you don't want the sizeof a pointer but the
    // size of a `node`:
    ListNode new_node = malloc(sizeof *new_node);

    new_node->size = size;
    new_node->link = NULL;

    if (*head == NULL) {           // corrected check (dereference head)
        *head = new_node;          // corrected assignment
    } else {
        ListNode current = *head;
        while (current->link != NULL) {
            current = current->link;
        }
        current->link = new_node;
    }
}

int main() {
    ListNode head = NULL;
    insert_node(&head, 10);
    insert_node(&head, 20);

    // the below loop had no exit condition before:
    for(ListNode ptr = head; ptr; ptr = ptr->link) {
        printf("%d ", ptr->size);
    }
    printf("\n");
}

Demo

稍微说明一下

typedef struct node {
    unint32_t size;
    struct node * link;
} *ListNode;

创建一个名为 ListNode 的类型。它是一个指向 struct node 的指针。这不是 struct node

所以当你这样做时

sizeof(ListNode) 

你得到的是指针的大小,而不是struct node

的大小

你需要做的

sizeof(struct node)

这是一件很常见的事情

typedef struct node {
    uint32_ size;
    struct node* link;
} *PListNode, ListNode;

这创建了 2 种类型

  • PlistNode 是指向 struct node
  • 的指针
  • ListNode 是一个 struct node

'P'提醒这是一个指针

所以现在你可以做

PListNode pn = malloc(sizeof(ListNode));