按价值打电话或按推荐打电话?

ᴜ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)

Tho*_*thy 5

C只有按值调用,所以(正式地)所有值都按值传递给函数.

但是,与其他数据相比,C中的数组处理方式略有不同,因此在第一个示例中,数组示例将转换为指向其第一个元素的指针,然后将该指针(通过值)传递给函数.

在第二个示例中,e是指向struct的指针(但它永远不会设置为指向任何位置),并将该指针(按值)传递给函数.

在这两种情况下,参数传递都是通过值完成的,但是当您将指针传递给变量时,被调用的函数可以对原始变量进行更改.


das*_*ght 5

在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)

  • 但如果它是`function(&e);`和`void function(struct example**e)`,而不是`*e = malloc(sizeof(struct example));`它是合法且有用的,对吧? (2认同)
  • @user将未初始化的指针传递给函数与声明相同类型的未初始化的局部变量相同.事实上,局部变量和参数之间的唯一区别是后者由调用者初始化,而前者在函数本身内初始化.调用`e = malloc(sizeof(struct example));`会让你使用`e`就好像它是一个常规的局部变量,而不会导致崩溃. (2认同)
  • 谢谢,我明白了.如果在`main()`我声明`struct example*e = NULL;`是否已初始化cosidered? (2认同)