猿问

如下,请问不是malloc子函数分配的内存在进程结束前不会自动free的吗?

我是想实现创建二叉树的,用前序式。但是我在子函数createtree中调用malloc分配内存,创建成功后回到主函数,分配的内存空间没有了。我在单步调试时创建时可以看见head的地址的,但函数返回main函数时地址就变回void*的了,不是malloc子函数分配的内存在进程结束前不会自动free的吗?
#include<stdio.h>
#include<stdlib.h>
typedef struct _tree
{
char data;
struct _tree *lchild;
struct _tree *rchild;
}bittree;
int createtree(bittree *head)
{
char data;
fscanf(stdin,"%c",&data);
getchar();
if('#' != data)
{
head = (bittree*)malloc(sizeof(bittree));
if(head == NULL) exit(0);
head->data = data;
head->lchild = NULL;
head->rchild = NULL;
createtree(head->lchild);
createtree(head->rchild);
}
return 1;

}
int main()
{
bittree *head = NULL;
createtree(head);
printf("root lchild data = %c\n",head->lchild->data);
return 1;

}

临摹微笑
浏览 201回答 2
2回答

慕后森

#include<stdio.h>#include<stdlib.h>typedef&nbsp;struct&nbsp;_tree{&nbsp;char&nbsp;data;&nbsp;struct&nbsp;_tree&nbsp;*lchild;&nbsp;&nbsp;struct&nbsp;_tree&nbsp;*rchild;}bittree;int&nbsp;createtree(bittree&nbsp;**head){&nbsp;char&nbsp;data;&nbsp;&nbsp;fscanf(stdin,"%c",&data);&nbsp;getchar();&nbsp;if('#'&nbsp;!=&nbsp;data)&nbsp;{&nbsp;&nbsp;*head&nbsp;=&nbsp;(bittree*)malloc(sizeof(bittree));&nbsp;&nbsp;if(*head&nbsp;==&nbsp;NULL)&nbsp;exit(0);&nbsp;&nbsp;(*head)->data&nbsp;=&nbsp;data;&nbsp;&nbsp;(*head)->lchild&nbsp;=&nbsp;NULL;&nbsp;&nbsp;(*head)->rchild&nbsp;=&nbsp;NULL;&nbsp;&nbsp;createtree((*head)->lchild);&nbsp;&nbsp;createtree((*head)->rchild);&nbsp;}&nbsp;return&nbsp;1;&nbsp;&nbsp;}int&nbsp;main(){&nbsp;bittree&nbsp;*head&nbsp;=&nbsp;NULL;&nbsp;createtree(&head);&nbsp;&nbsp;&nbsp;&nbsp;//这里传入head指针的地址,才可以在createtree里改变head的值&nbsp;printf("root&nbsp;lchild&nbsp;data&nbsp;=&nbsp;%c\n",head->lchild->data);&nbsp;return&nbsp;1;&nbsp;&nbsp;}C语言参数传递是值传递。你的createtree函数传入的是main函数里head变量的值,而head在createtree函数体内部却是个形参,形参的有效范围仅限于函数内部,所以你在createtree内部改变head的值,实际改变的是形参的值,并没有改变实参的值,也就是没有改变main函数里的head变量值。如果要在函数内部改变外部变量的值,两种方式:一种是不以参数形式在函数内部使用这个变量,即把这个变量定义成全局变量,直接在函数内部使用;一种是把这个变量的地址作为参数传进去,然后改变这个地址所在的内存空间,就相当于改变了这个变量的值。

手掌心

用二级指针, 或将开辟的空间返回
随时随地看视频慕课网APP
我要回答