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


c 跨函数 用指针申请内存

  Status getDepth(BiTree T, int **depth, int *count, int d) {
 if(T == NULL) 
 return OK;
    ++d;
    getDepth(T->lchild, depth, count, d);
    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;
}



其实发了一个帖子,但代码不够清晰,我又重新贴了张图


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


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


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


求达人指点。。。。


在此向 maxmin童鞋道歉 我不是有意的~~~~


 

c语言 函数 程序开发

Azusa酱 13 years ago

  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)

drdfg answered 13 years ago

Your Answer