如果我有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)
{
/ * ... */
}
这是第二个代码:
#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)
{
/ * ... */
}
这两个代码有什么区别?谢谢!
首先,将指针的地址传递给结构。 在第二个中,传递结构的地址。
在这两种情况下,function
都可以更改您传递的结构:
(*e)->x = 10; // First, needs additional dereferencing *.
e->x = 10; // Second.
首先,您还可以给main()
的e
一个不同的值,例如为其分配另一个结构的地址,或将其设置为 NULL
:
*e = NULL;
你实际上忘记了第三种情况:
function(struct example e) { ... }
在这里,该函数获取您传递它的结构的副本。
第一个例子可以改变'e'本身(例如Malloc()它并返回它)。如果"e"的位置不正确,这两个示例都可以更改其内容。
the structure
位于"云"中的某个地方。您正在处理指向它的指针,这些指针是包含the structure
地址的简单变量。在第一个示例中,您可以更改the pointer
和the structure
。在第二个示例中,您只能更改the structure
,而只能更改a pointer
(本地副本)。
当您在第二个示例中执行e = malloc ...
时,the structure
继续存在于"云"中,但您创建了一个新function
完成后会丢失其中的任何连接(= 内存泄漏)。从main
方面来说,一切都保持不变。
在C++中,您可以像这样更改第二个示例,void function (struct example *&e)
具有与第一个示例相同的行为,但可以舒适地自动取消引用"指针到指针"e(引用是某种自动取消引用指针)。