Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将结构指针传递给函数_C++_Pointers - Fatal编程技术网

C++ 将结构指针传递给函数

C++ 将结构指针传递给函数,c++,pointers,C++,Pointers,我有一个这样的结构 struct binTree{ long long data; struct binTree *left; struct binTree *right; } 还有这样一个函数: void height(struct binTree **r) { ... ... height(&(r->left)); height(&(r->right)); ... ... } 编译上述函数时会出现如下错误 err

我有一个这样的结构

struct binTree{
long long data;
struct binTree *left;
struct binTree *right;
}
还有这样一个函数:

void height(struct binTree **r)
{
    ...
    ...
    height(&(r->left));
    height(&(r->right));
    ...
    ...
}
编译上述函数时会出现如下错误

error: request for member ‘left’ in ‘* r’, which is of non-class type ‘binTree*’
error: request for member ‘right’ in ‘* r’, which is of non-class type ‘binTree*’
代码有什么问题?如何传递结构中的指针

你必须写作

height( &( ( *r )->left ) );
height( &( ( *r )->right ) );
或者更简单

height( &( *r )->left );
height( &( *r )->right );
这里的运算符&和*是一元运算符,其优先级低于后缀运算符,包括运算符->

另外,由于我认为这个函数不会改变对象binTree,那么您可以简化这个函数并将参数声明为

const struct binTree *r

或如果是C++程序,则

const binTree *r
在这种情况下,函数中使用的语法结构会更简单


只是我不明白为什么它有返回类型void。:函数不应该返回二叉树的高度,还是应该在函数体内部输出高度?如果函数返回高度,则更好。例如,在这种情况下,您可以比较两个二叉树的高度。

这是一种更清晰的语法:

void height(struct binTree **r)
{
    struct binTree* pr = *r;
    height( &pr->right );
    height( &pr->left );
}

为什么高度函数需要采用binTree**而不仅仅是binTree*?如果需要修改输入指针,只需要双间接。建议你学习一些C++书籍,以避开C或将问题标记为C,只。