【问题标题】:Returning an integer array pointer in C在C中返回一个整数数组指针
【发布时间】:2014-06-28 21:42:33
【问题描述】:

我正在尝试返回一个指向整数数组的指针,该数组表示将数组中的每个函数应用于值 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 result[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: 警告: (near “结果”的初始化)[默认启用] prog.c:41:2: 警告:数组初始值设定项中的多余元素 [默认启用] prog.c:41:2:警告:(接近初始化“结果”)[启用 默认] prog.c:41:2:警告:数组初始值设定项中的多余元素 [默认启用] prog.c:41:2: 警告: (接近初始化 ‘result’) [默认启用] prog.c:42:2: warning: return from 不兼容的指针类型 [默认启用] 返回 &result; ^ prog.c:42:2:警告:函数返回局部变量的地址 [-Wreturn-local-addr]

【问题讨论】:

  • 您意识到result 在函数返回时超出范围,因此无法使用?
  • 我明白了,我如何返回一个可用的数组,所以我可以说打印出 main 方法中的内容?
  • 或者传递一个指向函数将填充的数组的指针。 C 做输出参数的方式。
  • Malloc 数组并返回指向动态分配内存的指针。或者,将指向数组的指针传递给函数并让函数填充/初始化它。
  • 无法在VLA中写入初始化列表。

标签: c


【解决方案1】:

当你这样做时

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;
}

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

【讨论】:

    【解决方案2】:

    不能使用初始化列表初始化可变长度数组。

    这样做

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

    不是有效的 C。

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多