如何从C函数中生成数组返回类型?

use*_*249 15 c

我试图返回数组名称,如下所示.基本上我试图让函数测试返回一个可以在main中使用的数组.你能告诉我需要阅读的内容,以了解如何执行这样的功能吗?

#include <stdio.h>

int test(int size, int x){
    int factorFunction[size];    
    factorFunction[0] = 5 + x;
    factorFunction[1] = 7 + x;
    factorFunction[2] = 9 + x;
    return factorFunction;
}

int main(void){
    int factors[2];
    factors = test(2, 3);
    printf("%d", factors[1]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我收到编译器错误:

smallestMultiple.c:8: warning: return makes integer from pointer without a cast
smallestMultiple.c:8: warning: function returns address of local variable
smallestMultiple.c: In function ‘main’:
smallestMultiple.c:13: error: incompatible types in assignment
Run Code Online (Sandbox Code Playgroud)

Oli*_*rth 13

函数无法在C中返回数组.

但是,它们可以返回结构.结构可以包含数组......

  • @MohdShibli - 在大多数情况下,这并不是真正的解决方案。静态是单例,这意味着一旦你第二次调用它,你就不能继续使用第一个函数调用的结果。 (2认同)

Som*_*ude 13

您可以通过返回指针返回一个数组(数组衰减到指针).但是,在您的情况下这将是不好的,因为那时您将返回指向局部变量的指针,并导致未定义的行为.这是因为返回的指针指向的内存在函数返回后不再有效,因为堆栈空间现在被其他函数重用.

你应该做的是将数组及其大小作为参数传递给函数.

您的代码中还有另一个问题,那就是使用大小为2的数组,但写入第三个元素.


Ini*_*eer 9

您需要在堆上分配内存并返回指针.C不能从函数返回数组.

int* test(int size, int x)
{
    int* factorFunction = malloc(sizeof(int) * size);    
    factorFunction[0] = 5 + x;
    factorFunction[1] = 7 + x;
    factorFunction[2] = 9 + x;
    return factorFunction;
}
Run Code Online (Sandbox Code Playgroud)