ᴜsᴇ*_*sᴇʀ 4 c struct pointers reference
在下面的代码中,我向函数传递指针*example[10];或整个数组?
#include <stdio.h>
void function (int **)
int main ()
{
int *example[10];
function(example);
return 0;
}
void function (int *example[10])
{
/* ... */
return;
}
Run Code Online (Sandbox Code Playgroud)
以下代码的相同问题:
#include <stdio.h>
struct example
{
int ex;
};
void function (struct example *)
int main ()
{
struct example *e;
function(e);
return 0;
}
void function (struct example *e)
{
/* ... */
return;
}
Run Code Online (Sandbox Code Playgroud)
C只有按值调用,所以(正式地)所有值都按值传递给函数.
但是,与其他数据相比,C中的数组处理方式略有不同,因此在第一个示例中,数组示例将转换为指向其第一个元素的指针,然后将该指针(通过值)传递给函数.
在第二个示例中,e是指向struct的指针(但它永远不会设置为指向任何位置),并将该指针(按值)传递给函数.
在这两种情况下,参数传递都是通过值完成的,但是当您将指针传递给变量时,被调用的函数可以对原始变量进行更改.
在C中,所有参数都按值传递,包括指针.在传递数组的情况下,数组"衰减"到指向其初始元素的指针.
你的第一个函数传递一个指向十个单位指针块的指针int.这可能很有用,因为function(int**)可以将数组内的指针更改为有效指针.例如,允许这样做:
void function (int *example[10])
{
for (int i = 0 ; i != 10 ; i++) {
// Allocate a "triangular" array
example[i] = malloc((i+1)*sizeof(int));
}
}
Run Code Online (Sandbox Code Playgroud)
(当然调用者现在负责所有这些分配的内存)
你的第二个函数传递一个未初始化的指针.这完全没用,因为function(struct example *e)既不能合法地分配也不取消引用这个指针.
这将是非法的:
void function (struct example *e)
{
e->ex = 123; // UNDEFINED BEHAVIOR! e is uninitialized
}
Run Code Online (Sandbox Code Playgroud)
这不会e对调用者的值产生影响:
void function (struct example *e)
{
e = malloc(sizeof(struct example)); // Legal, but useless to the caller
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
579 次 |
| 最近记录: |