为什么函数可以通过malloc返回数组设置,但不能通过"int cat [3] = {0,0,0};"返回一个设置.

Kri*_*son 3 c variables malloc scope

为什么我可以通过malloc从函数返回数组设置:

int *dog = (int*)malloc(n * sizeof(int));
Run Code Online (Sandbox Code Playgroud)

但不是由数组设置

 int cat[3] = {0,0,0};
Run Code Online (Sandbox Code Playgroud)

返回"cat []"数组并显示警告.

感谢你的帮助

kep*_*aro 7

这是一个范围问题.

int cat[3]; // declares a local variable cat
Run Code Online (Sandbox Code Playgroud)

局部变量与malloc内存

堆栈上存在局部变量.当此函数返回时,将销毁这些局部变量.此时,用于存储阵列的地址将被回收,因此您无法保证其内容的任何内容.

如果你调用malloc,你将从堆中分配,因此内存将持续超出函数的生命周期.

如果该函数应该返回一个指针(在这种情况下,指向整数数组的第一个地址指针),该指针应该指向良好的内存.Malloc是确保这一点的方法.

避免Malloc

您不必在函数内部调用malloc(尽管这样做是正常和适当的).

或者,您可以将一个地址传递给您应该保存这些值的函数.你的函数将完成计算值的工作,并将填充给定地址的内存,然后它将返回.

实际上,这是一种常见的模式.但是,如果这样做,您会发现不需要返回地址,因为您已经知道正在调用的函数之外的地址.因此,返回一个表示例程成功或失败的值(比如int)更常见,而不是返回相关数据的地址.

这样,函数的调用者可以知道数据是否已成功填充或是否发生错误.

#include <stdio.h>             // include stdio for the printf function

int rainCats (int *cats);      // pass a pointer-to-int to function rainCats

int main (int argc, char *argv[]) {

    int cats[3];               // cats is the address to the first element

    int success;               // declare an int to store the success value
    success = rainCats(cats);  // pass the address to the function

    if (success == 0) {
        int i;
        for (i=0; i<3; i++) {
            printf("cat[%d] is %d \r", i, cats[i]);
            getchar();
        }
    }

    return 0;
}

int rainCats (int *cats) {
    int i;
    for (i=0; i<3; i++) {      // put a number in each element of the cats array
        cats[i] = i;
    }
    return 0;                  // return a zero to signify success
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样

请注意,你从来没有必要在这里调用malloc,因为cat [3]是在main函数内部声明的.main中的局部变量只有在程序退出时才会被销毁.除非程序非常简单,否则malloc将用于创建和控制数据结构的生命周期.

还要注意,rainCats是硬编码到返回0,没有任何反应rainCats这将使其失效,比如试图访问一个文件,一个网络请求,或其他内存分配的内部.更复杂的程序有许多失败的原因,因此返回成功代码通常是有充分理由的.