使用链表保存结构体,结构体只有一个成员num。
重点理解:
- 在分配动态内存空间,返回值是指针。导致不太好理解了,万恶之源!!
- 为什么head_pointer是指向<结构体指针>的指针:结构体存储在堆中,访问都要靠指针,内层的<结构体指针>其实与可以理解成与局部变量是一致的,只不过一个是变量本身,一个是指针。
- 因为上面这两个问题,才导致add函数中,传入参数是指针的指针。
- 其实明确一个原则就可以:使用指针进行参数传递时,想访问谁就传递谁的指针。
#include <stdio.h>
#include <stdlib.h>
// define struct Node
struct Node
{
int num;
struct Node *next;
};
void get_info(struct Node *node)
{
printf("Please enter the num: ");
scanf("%d", &node -> num);
}
void addNode(struct Node **head_pointer)//(*head_pointer)是定义一个结构体指针,*(*(head_pointer))就是定义一个指向结构体指针的指针;*表示定义指针
{
struct Node *temp;
// instruct a new node
struct Node *node = (struct Node *)malloc(sizeof(struct Node)); // 创建一个node
// write information in the new object
get_info(node);
// make the head_pointer point to the new object
if (*head_pointer != NULL)
{
temp = *head_pointer;
*head_pointer = node; //*表示解引用,head_pointer是一个指向结构体指针的指针,一层解引用就是结构体指针,使结构体指针指向node,也就是新插入的对象node
node -> next = temp;
}
else
{
*head_pointer = node;// 只要是修改值,就是*(指针名)
node -> next = NULL;
}
}
void printNode(struct Node *head_pointer)
{
struct Node *node;
int count = 1;
node = head_pointer;
while (node != NULL)
{
printf("---Node Sequence Number: %d---\n", count);
printf("\tNum: %d\n", node -> num);
node = node -> next;
count++;
}
}
void releaseNode(struct Node *node)
{
struct Node *temp;
while(node != NULL)
{
temp = node -> next; //node是指针,第一次node存有第一个元素的地址,因此node->就是第二个元素的地址
free(node);
node = temp;
}
}
int main()
{
char ch;
struct Node *head_pointer;
head_pointer = NULL; // 指针初始化,指向指向地址NULL
while(1)
{
printf("Do you need enter num(Y/N)?");
do
{
ch =getchar();
} while(ch != 'Y' && ch != 'N');
if (ch == 'Y')
{
addNode(&head_pointer); // 总之,想访问谁的值就传入谁的地址
}
else
{
break;
}
}
printf("Do you need to print the information? (Y/N):");
do
{
ch =getchar();
} while(ch != 'Y' && ch != 'N');
if (ch == 'Y')
{
printNode(head_pointer); //为什么不取head_pointer地址了?因为想访问的不是head_pointer本身,而是他指向的对象。想访问第一个对象,因此把第一个对象的地址,也就是head_pointer传过去。
}
releaseNode(head_pointer);
return 0;
}
网友评论