读书人

c 跨函数 用指针申请内存储器

发布时间: 2013-08-09 15:16:24 作者: rapoo

c 跨函数 用指针申请内存



主要问题是:我在主函数里声明了一个int *depth;然后把&depth作为参数传给该函数,但不知为何只能求出第一个叶子节点到根节点的路径长度。

我单步调试了,在该函数内部的时候 申请空间以及计算高度都是正确的。

问题可能就是跨函数用指针申请内存,但我实在不知道错在哪里了。。。

求达人指点。。。。

在此向 max_min_童鞋道歉c 跨函数 用指针申请内存储器我不是有意的~~~~

内存 递归? C 指针
[解决办法]
static int _getCount(BiTree T)
{
if (NULL == T)
return 0;
return getCount(T->lchild) + getCount(T->rchild) + 1;
}

static int *_getDepth(BiTree T, int *depth, int d)
{
if (NULL == T)
return depth;

*depth++ = d;
depth = getDepth(T->lchild, depth, d + 1);
depth = getDepth(T->rchild, depth, d + 1);
return depth;
}

Status getDepth(BiTree T, int **depth, int *count, int d)
{
int n = _getCount(T);
*depth = malloc(n * sizeof(int));
if (NULL == *depth)


return OVERFLOW;
*count = n;
_getDepth(T, *depth, d);
return OK;
}


[解决办法]

Status getDepth(BiTree T, int **depth, int *count, int d) {
if(T == NULL)
return OK;
++d;
getDepth(T->lchild, depth, count, d);//还是这里问题,你if条件不
//成立,然后递归,然后在判断再递归,到if条件成立 退出函数?你这函数是这公呢能么?
if(T->lchild == NULL && T->rchild == NULL) {
depth[*count] = (int *)malloc(sizeof(int));
if (!depth[*count])
exit(OVERFLOW);
*(depth[*count]) = d;
(*count) ++;
}
getDepth(T->rchild, depth, count, d);
--d;
}

[解决办法]
“给定一个小点的输入,完整单步跟踪(同时按Alt+7键查看Call Stack里面从上到下列出的对应从里层到外层的函数调用历史)一遍。”是理解递归函数工作原理的不二法门!
递归函数关注以下几个因素
退出条件
参数有哪些
返回值是什么
局部变量有哪些
全局变量有哪些
何时输出
会不会导致堆栈溢出

读书人网 >C语言

热点推荐