在C中返回整数数组指针

时间:2014-05-11 14:08:55

标签: c

我正在尝试返回一个指向整数数组的指针,这些整数表示将数组中的每个函数应用于值n的结果。

#include <math.h>
#include <stdio.h>

typedef int (*funT)(int);
int *mapApply(int n, funT fs[], int size);
int func1(int);
int func2(int);
int func3(int);
int func4(int);
int func5(int);

int main() {

    funT array[5] = { func1, func2, func3, func4, func5 };
    mapApply(2, array, 5 );

    return 0;
}

int func1 (int n) {
    return n + 1;
}

int func2 (int n) {
    return n + 2;
}

int func3 (int n) {
    return n + 3;
}

int func4 (int n) {
    return n + 4;
}

int func5 (int n) {
    return n + 5;
}

int *mapApply(int n, funT fs[], int size) {
    int result[size] = { fs[0](n), fs[1](n), fs[2](n), fs[3](n), fs[4](n) };
    return &result;
}

目前我的mapApply功能不起作用。这是编译错误:

  

prog.c:在函数'mapApply'中:prog.c:41:2:错误:变量大小   对象可能未初始化为int [size] = {fs0,   fs1,fs2,fs3,fs4}; ^ prog.c:41:2:警告:   数组初始值设定项中的多余元素[默认启用] prog.c:41:2:   警告:(接近初始化'结果')[默认启用]   prog.c:41:2:警告:数组初始化程序中的多余元素[启用   默认值] prog.c:41:2:警告:(接近初始化'结果')   [默认启用] prog.c:41:2:警告:数组中的多余元素   初始化程序[默认启用] prog.c:41:2:警告:(近   初始化'结果')[默认启用] prog.c:41:2:   警告:数组初始值设定项中的多余元素[默认启用]   prog.c:41:2:警告:(接近初始化'结果')[启用   默认值] prog.c:41:2:警告:数组初始值设定项中的多余元素   [默认启用] prog.c:41:2:警告:(接近初始化时为   'result')[默认启用] prog.c:42:2:警告:从中返回   不兼容的指针类型[默认启用] return&amp; result; ^   prog.c:42:2:warning:函数返回局部变量的地址   [-Wreturn本地-ADDR]

2 个答案:

答案 0 :(得分:4)

当你这样做时

int *mapApply(int n, funT fs[], int size) {
    int result[size] = { fs[0](n), fs[1](n), fs[2](n), fs[3](n), fs[4](n) };
    return &result;
}

你有两个错误:

  • 指向result的指针与mapApply的返回类型不兼容,
  • 您正在尝试返回指向本地数组的指针。

要解决此问题,您需要动态分配数组,或者将缓冲区传递给函数。以下是动态分配数组的方法:

int *mapApply(int n, funT fs[], int size) {
    int *result = malloc(sizeof(int)*size);
    for (int i = 0 ; i != 5 ; i++) {
        result[i] = fs[i](n);
    }
    return result;
}

调用者需要free manApply调用的结果,以避免内存泄漏。

答案 1 :(得分:1)

无法使用初始化列表初始化可变长度数组。

这样做

size_t s = 4;
int a[s] = {1, 2, 3, 4};

无效C.