【问题标题】:struct example *e: differences between function(&e) and function(e)struct 示例 *e:function(&e) 和 function(e) 之间的区别
【发布时间】:2014-01-16 15:37:16
【问题描述】:

如果我有struct example *efunction(&e)function(e) 有什么区别?

一个例子。

这是第一个代码:

#include <stdio.h>

struct example
{
    int x;
    int y;
};

void function (struct example **);

int main ()
{
    struct example *e;

    function (&e);

    return 0;
}

void function (struct example **e)
{
    / * ... */
}

这是第二个代码:

#include <stdio.h>

struct example
{
    int x;
    int y;
};

void function (struct example *);

int main ()
{
    struct example *e;

    function (e);

    return 0;
}

void function (struct example *e)
{
    / * ... */
}

这两个代码有什么区别? 谢谢!

【问题讨论】:

    标签: c function struct


    【解决方案1】:

    first 中,您将指针的地址传递给结构。在 second 中传递结构的地址。

    在这两种情况下function 都可以改变你传递给它的结构:

    (*e)->x = 10; // First, needs additional dereferencing *.
    
    e->x    = 10; // Second.
    

    首先,你也可以给main()e一个不同的值,例如分配另一个结构的地址给它,或者将它设置为NULL

    *e = NULL;
    

    你实际上忘记了第三个案例:

    function(struct example e) { ... }
    

    这里函数获取你传递给它的结构的副本。

    【讨论】:

    • 但是在第二种情况下我可以在函数中执行e = malloc ( 2 * sizeof(struct example)) 吗?
    • @user 可以,但您只能在函数中本地更改e。函数参数e是传值的。
    • 好的,如果我在第一个*e = malloc ( 2 * sizeof(struct example)) 中更改它,我也会在main() 中更改它,对吧?
    • @user 实际上,使用*e,您基本上是在访问main()e
    • @meaning-matters在这两种情况下,函数都可以改变你传递给它的结构 但是在第二种情况下,我为什么要修改结构呢?
    【解决方案2】:

    第一个示例可以更改 'e' 本身(例如 Malloc() 并返回它)。 如果是 malloced,这两个示例都可以更改 'e' 的内容。

    【讨论】:

    • @Peter Miehle。你的意思是在第一个代码中我可以在函数中 malloc,例如 *e = malloc ( 2 * sizeof(struct example)); 而在第二种情况下不是?
    【解决方案3】:

    the structure 在“云”中的某个地方。您正在处理指向它的指针,它们是保存the structure 地址的简单变量。在第一个示例中,您可以更改 the pointerthe structure。在第二个示例中,您只能将 the structure 更改为 a pointer(本地副本)。

    当您在第二个示例中执行e = malloc ... 时,the structure 继续存在于“云”中,但您创建了一个新的,当function 完成时您将失去任何连接(= memory-泄漏)。从main的角度来看,一切都保持不变。

    在 C++ 中,您可以像 void function (struct example *&amp;e) 一样更改第二个示例,使其具有与第一个示例相同的行为,但可以轻松地自动取消引用“指针到指针”e(引用是某种自动取消引用指针)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      • 2018-05-30
      • 2013-09-29
      • 1970-01-01
      相关资源
      最近更新 更多