#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
head = (struct node*)malloc(sizeof(struct node));
second = (struct node*)malloc(sizeof(struct node));
third = (struct node*)malloc(sizeof(struct node));
head->data = 1; //assign data in first node
head->next = second; // Link first node with the second node
second->data = 2; //assign data to second node
second->next = third;
third->data = 3; //assign data to third node
third->next = NULL;
return 0;
}
我是新手指針,我發現這個代碼在書中創建鏈表。我不明白爲什麼主函數中的前三行代碼是必需的。爲什麼我們要求指向節點的指針是空指針? 任何幫助將不勝感激,因爲這個概念對我來說似乎很難。創建三個節點的鏈表
它只是指針變量的聲明,因爲許多編譯器會拋出一個錯誤爲未初始化的 – piyushj
但是爲什麼NULL是特別的? – user34304
沒有理由對它們進行初始化。在現代C中,甚至沒有必要將它們與'malloc'分開;你可以寫'struct * node head = malloc(sizeof(struct node));' 用'NULL'指針進行初始化並不是真正值得推薦的地方,它只是讓編譯器難以產生正確的診斷。例如。它不能抱怨未初始化的變量,因爲它們現在已經初始化了。 –