c语言用双重指针在无需返回的情况下于函数中创建链表,关于c语言用双重指针在无需返回的情况下于函数中创建链表的一点小小发现...

我们都知道在c语言中创建链表的一章标准的例子是这样的:

struct student  *creat(void)

{

struct  struct *head;

struct student *p1,*2;

p1=p1=(struct student *)malloc(sizeof(struct student);

while()

{

.......

}

........

rerurn (head);

}

除了这种方法还可以不要返回return (head)

但是要用双重指针**p来操作;否则是不会创建成功的(这个一般知识就不解释了)。

后来我想为什么双重指针就可以呢?而且今天老师讲的数据结构涉及到这个问题,但是她没有又讲清楚。绕的大家晕晕的......

吃饭时我仔细想了一下用一维指针*p时,让它来指向开辟的空间这个无非就是在函数结束的时候被释放掉了访问权限。即使是传指的方式也不会再函数外面访问到这块malloc出来的区域。然而用**p  p=&head;void fuction(p);(伪代码)来操作时就可以在不返回p的情况下在函数fuction外面利用head就能访问的malloc出来的区域。这个我回来验证了一下。我想应该是这样的:函数局部变量(这里是局部指针变量)在函数调用结束后会释放掉。但是他释放的不是说是只要是在函数里面声请的每一块都会释放掉,而是释放掉“最外层的指针”。也就是说应使用*p传指时,函数调用结束后会释放掉p与其指向的区域的“联系”,用**p来处理是会释放掉p与其指向的区域,这里的释放是切断了p与

#include

typedef struct node

{

int element;

struct node *next;

}date;

void main()

{

date *head;

int lable;

int fuction(date *p);

head=NULL;

lable=fuction(head);

head=lable;

printf("%d\n",head->element);

getch();

clrscr();

}

int fuction(date *p)

{

int temp;

p=(date *)malloc(sizeof(date));

p->element=4;

p->next=NULL;

temp=p;

return temp;

}

头指针head的联系,不影响头指针head与开辟的内存区域的联系。所以虽然p与head的联系释放掉了,但是不影响到head来访问开辟的内存区域。

这是我的一点见解,验证程序是:

#include

typedef struct node

{

int element;

struct node *next;

}date;

void main()

{

date *head;

void fuction(date *p);

head=NULL;

fuction(head);

printf("%d\n",head->element);

getch();

clrscr();

}

void fuction(date *p)

{

p=(date *)malloc(sizeof(date));

p->element=4;

p->next=NULL;

}

结果是 0;

第二个是用整形变量来标记被释放区域首地址如下:

#include

typedef struct node

{

int element;

struct node *next;

}date;

void main()

{

date *head;

int lable;

int fuction(date *p);

head=NULL;

lable=fuction(head);

head=lable;

printf("%d\n",head->element);

getch();

clrscr();

}

int fuction(date *p)

{

int temp;

p=(date *)malloc(sizeof(date));

p->element=4;

p->next=NULL;

temp=p;

return temp;

}

结果是 4;

双重指针的验证

#include

typedef struct node

{

int element;

struct node *next;

}date;

void main()

{

date *head;

int lable;

int fuction(date **p);

head=NULL;

lable=fuction(&head);

head=lable;

printf("%d\n",head->next->element);

getch();

clrscr();

}

int fuction(date **p)

{

int temp;

*p=(date *)malloc(sizeof(date));

(*p)->element=4;

(*p)->next=NULL;

temp=p;

return temp;

}

结果也是0;

与上面一个对比代码

#include

typedef struct node

{

int element;

struct node *next;

}date;

void main()

{

date *head;

int lable;

int fuction(date **p);

head=NULL;

lable=fuction(&head);

head=lable;

printf("%d\n",head->element);

getch();

clrscr();

}

int fuction(date **p)

{

int temp;

*p=(date *)malloc(sizeof(date));

(*p)->element=4;

(*p)->next=NULL;

temp=*p;

return temp;

}

结果是4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值