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

ᴜsᴇ*_*sᴇʀ 3 c struct function

如果我有struct example *e,那么function(&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)
{
    / * ... */
}
Run Code Online (Sandbox Code Playgroud)

这是第二个代码:

#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)
{
    / * ... */
}
Run Code Online (Sandbox Code Playgroud)

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

mea*_*ers 6

在第一个中,您将指针的地址传递给结构.在第二个中,您传递结构的地址.

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

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

e->x    = 10; // Second.
Run Code Online (Sandbox Code Playgroud)

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

*e = NULL;
Run Code Online (Sandbox Code Playgroud)

你实际上忘记了第三种情况:

function(struct example e) { ... }
Run Code Online (Sandbox Code Playgroud)

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