这段代码是如何工作的"head->next = second;"?


#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head;
struct node *second;
struct node *third;
head = (struct node *)malloc(sizeof(struct node));
second = (struct node *)malloc(sizeof(struct node));
third = (struct node *)malloc(sizeof(struct node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
head->next = NULL;
return 0;
}

我不明白下一个是如何获得第二值的??我的意思是我没有顺序,这是否意味着秒的值进入下一个,头指向下一个?

它的工作原理是这样的:

head = (struct node *)malloc(sizeof(struct node));
second = (struct node *)malloc(sizeof(struct node));
third = (struct node *)malloc(sizeof(struct node));

假设所有malloc都成功,内存中的视图将是这样的 -

head---+
|
+-------+
|   |   |
+-------+
second---+
|
+-------+
|   |   |
+-------+
third---+
|
+-------+
|   |   |
+-------+
====================================
head->data = 1;
head->next = second;
// After execution of these statements
head---+
|
+-------+
| 1 |   |---+
+-------+   |        // now memory referred by pointer second
|        // is also referred by head->next pointer
second---+ +--------+
| | 
+-------+
|   |   |
+-------+
third---+
|
+-------+
|   |   |
+-------+
====================================
second->data = 2;
second->next = third;
// After execution of these statements
head---+
|
+-------+
| 1 |   |---+
+-------+   |        // second->data == head->next->data
|
second---+ +--------+
| | 
+-------+
| 2 |   |---+
+-------+   |        // now memory referred by pointer third
|        // is also referred by second->next pointer
third---+ +--------+
| | 
+-------+
|   |   |
+-------+

====================================
third->data = 3;
head->next = NULL;     // did you mean third->next = NULL !
// After execution of these statements
head---+
|
+-------+
| 1 |   |--->NULL    // head->next = NULL will break the link 
+-------+            // between pointer and memory area it was
// referring to
second---+ 
|  
+-------+
| 2 |   |---+
+-------+   |
|
third---+ +--------+
| | 
+-------+
| 3 |   |
+-------+

每个结构节点都是具有两个变量的数据结构:

  • 整数值
  • 指向另一个节点结构的指针
本质上,通过以下指令,名为"head"的节点的">

next"变量将采用名为"second"的节点的地址:

head->next = second;

head是指向使用malloc动态分配的结构的指针。

head->next只是(*head).next的捷径。

head正在访问它所指向的结构的成员,并将其设置为指向second,这是指向head指向的相同类型的struct的指针。您在其中找到此代码的文档对此进行了详细解释。

旁白:演员阵容是多余的。C会自动将返回的void指针提升为正确的类型。 您还应该检查malloc的返回值以查看它是否成功。尝试取消引用不确定或NULL指针具有未定义的行为。

最新更新