学习到单链表时,对于结构结构指针作为函数的参数有些许困惑,故借以码单链表(不带头结点)名义实验下心中的困惑。
·Q:
在函数中,参数使用结构,那么该结构内的指针指向的内存被修改是否会修改。
·猜测:
不会∵结构内的指针也是结构的一部分其传参传得是结构其内部置针也会被复制,所以更改的只是复制部分.
·实验结论:
会改变,虽然复制了一个结构但是该结构内的指针变量和原结构指针变量相同,所以通过指针指向的数据内存都是同一个,所以同样可以达到更改数据的目的。就相当于指针的指针
·实验代码:
//
// main.c
// 单链表(不带头结点)_插入与删除
//
// Created by 郭宸羽 on 30/7/2022.
//
#include <stdio.h>
#include <stdlib.h>
//创建结点属性
typedef struct SLNode
{
int data;
struct SLNode *next;
}SLNode,*SingleLinkList_p;
//创建链表信息属性
typedef struct InfomOfSLL
{
int ll_length;
SingleLinkList_p SLL_p;
}InfomOfSLL;
//初始化单链表(不带头结点)
int InitialSLL(InfomOfSLL*SLL,int arr[])
{
//for the strong of the function test the legal number of linklist length before create
if(SLL->ll_length>=1)
{
//o先创建第一个结点,然后创建控制节点指针指向第一个结点,then loop for create SingleLinklist
//·声明结点指针tem用于创建结点,并将单链表的SingleLinkList_p指向(初始化)第一个结点
SLNode*tem=(SingleLinkList_p)malloc(sizeof(SLNode));//从堆区开辟内存用于结点
tem->next=NULL;//初始化结点指针域
//·通过数组进行赋值,变量i在循环创建链表时用于赋值
int i=0;
tem->data=arr[i];
SLL->SLL_p=tem;//将链表头与外部指针链接
SLNode* control_p=tem;//创建临时控制指针,用于循环中创建链表时节点的链接
//o循环控制创建链表
for(i=1;i<SLL->ll_length;i++)//已将完成了第一个节点的创建故将i初始值不设为0而是1
{
tem =(SingleLinkList_p)malloc(sizeof(SLNode));
//·creat and initialize new node
tem->data=arr[i];
tem->next=NULL;//This will be more easily for create the end of the linklist pointer arrange in the loopcreate;
//·link the older Linklist end node to the new node
control_p->next=tem;
//·switch control_p to next looptime link
control_p=tem;
}
return 1;
}
else
{
printf("The legal arrange number of length is[1,∞],and please check you number");
return -1;
}
return 1;
}
void Display(InfomOfSLL SLL)
{
for(int i=0;i < SLL.ll_length;i++)
{
SLL.SLL_p->data++;
//Test——在函数中,参数使用结构,那么该结构内的指针指向的内存被修改是否会修改。猜测:不会,∵结构内的指针也是结构的一部分其传参传得是结构其内部置针也会被复制,所以更改的只是复制部分.
//AN:会改变,虽然复制了一个结构但是该结构内的指针变量和原结构指针变量相同,所以通过指针指向的数据内存都是同一个,所以同样可以达到更改数据的目的。就相当于指针的指针
printf("[%d]->",SLL.SLL_p->data);
}
printf("\n");
}
int main()
{
InfomOfSLL SLL1;
SLL1.ll_length=6;
int arry1[6]={1,2,3,4,5,6};
InitialSLL(&SLL1, arry1);
Display(SLL1);
Display(SLL1);
}