gpt4 book ai didi

c - 什么时候使用双指针?

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:21 24 4
gpt4 key购买 nike

我看到了将树转换为其镜像的工作代码。

struct node* mir(struct node *root)
{
if(root)
{

struct node * temp;
mir(root->left);
mir(root->right);
temp=root->left;
root->left=root->right;
root->right=temp;
}

不应该像我们在链表中那样存在 mir(struct node **) 吗?

最佳答案

C 中的所有调用都是按值调用,这意味着被调用函数不能更改调用者上下文中参数的值。被调用函数只接收参数的副本。但是,您可以通过将指针传递给您的变量,然后修改其解引用状态来有效地绕过它。如果要更改的变量是指针怎么办?您将指针传递给指针。

struct node* mir(struct node *root);
struct node* mir2(struct node **root);
...
/* following cannot change value of root */
x = mir(root);
/* following may change value of root */
x = mir2(&root);

关于c - 什么时候使用双指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30750721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com