臨摹微笑
2022-03-18 09:11:21
我是想實(shí)現(xiàn)創(chuàng)建二叉樹(shù)的,用前序式。但是我在子函數(shù)createtree中調(diào)用malloc分配內(nèi)存,創(chuàng)建成功后回到主函數(shù),分配的內(nèi)存空間沒(méi)有了。我在單步調(diào)試時(shí)創(chuàng)建時(shí)可以看見(jiàn)head的地址的,但函數(shù)返回main函數(shù)時(shí)地址就變回void*的了,不是malloc子函數(shù)分配的內(nèi)存在進(jìn)程結(jié)束前不會(huì)自動(dòng)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;}
2 回答

慕后森
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
#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); //這里傳入head指針的地址,才可以在createtree里改變head的值 printf ( "root lchild data = %c\n" ,head->lchild->data); return 1; } |
C語(yǔ)言參數(shù)傳遞是值傳遞。
你的createtree函數(shù)傳入的是main函數(shù)里head變量的值,而head在createtree函數(shù)體內(nèi)部卻是個(gè)形參,形參的有效范圍僅限于函數(shù)內(nèi)部,所以你在createtree內(nèi)部改變head的值,實(shí)際改變的是形參的值,并沒(méi)有改變實(shí)參的值,也就是沒(méi)有改變main函數(shù)里的head變量值。
如果要在函數(shù)內(nèi)部改變外部變量的值,兩種方式:一種是不以參數(shù)形式在函數(shù)內(nèi)部使用這個(gè)變量,即把這個(gè)變量定義成全局變量,直接在函數(shù)內(nèi)部使用;一種是把這個(gè)變量的地址作為參數(shù)傳進(jìn)去,然后改變這個(gè)地址所在的內(nèi)存空間,就相當(dāng)于改變了這個(gè)變量的值。
添加回答
舉報(bào)
0/150
提交
取消