struct example * e:函数(& e)和函数(e)之间的差异

时间:2014-01-16 15:37:17

标签: c function struct

如果我有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)
{
    / * ... */
}

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

3 个答案:

答案 0 :(得分:6)

第一个中,您传递指向结构的指针的地址。在第二个中,您传递结构的地址。

在这两种情况下,function都可以更改您传递的结构:

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

e->x    = 10; // Second.

在第一个中,您还可以为main()的{​​{1}}提供不同的值,例如为其分配另一个结构的地址,或将其设置为e

NULL

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

*e = NULL;

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

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

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

在C ++中你可以改变你的第二个例子,就像这个void function (struct example *&e)一样,具有与第一个相同的行为,但是它具有“指向指针”e的自动解除引用的舒适性(引用是某种排序)自动取消引用指针)。