c - 从 C 中的函数返回多维数组

标签 c arrays function pointers multidimensional-array

从 c 中的函数返回多维数组的最佳方法是什么?

假设我们需要在一个函数中生成一个多维数组并在 main 中调用它,最好将它包装在一个结构中还是只返回一个指向堆上内存的指针?

 int *create_array(int rows, int columns){
     int array[rows][columns] = {0};
     return array;
 }

 int main(){

     int row = 10;
     int columns = 2;
     create_array(row,columns); 
 }

上面的代码,只是勾勒出我心目中的基本程序。

最佳答案

这是错误的:

int *create_array(int rows, int columns){
     int array[rows][columns] = {0};
     return array;
}

并且应该产生这样的警告:

prog.c:2:6: note: (near initialization for 'array')
prog.c:3:13: warning: return from incompatible pointer type [-Wincompatible-pointer-types]
      return array;
             ^~~~~
prog.c:3:13: warning: function returns address of local variable [-Wreturn-local-addr]

因为您要返回一个自动变量的地址;当相应的功能终止时,它的生命周期结束。


您应该在 main() 中声明一个双指针,通过函数传递它,为其动态分配内存并返回该指针。或者您可以在 main() 中创建数组并将双指针传递给该函数。


I want to know ways to allocate multidimensional arrays on the heap and pass them around

要在堆上分配内存,您可以使用这两种方法之一,其中涉及指针:

#include <stdio.h>
#include <stdlib.h>

// We return the pointer
int **get(int N, int M) /* Allocate the array */
{
    /* Check if allocation succeeded. (check for NULL pointer) */
    int i, **array;
    array = malloc(N*sizeof(int *));
    for(i = 0 ; i < N ; i++)
        array[i] = malloc( M*sizeof(int) );
    return array;
}

// We don't return the pointer
void getNoReturn(int*** array, int N, int M) {
    /* Check if allocation succeeded. (check for NULL pointer) */
    int i;
    *array = malloc(N*sizeof(int *));
    for(i = 0 ; i < N ; i++)
        (*array)[i] = malloc( M*sizeof(int) );
}

void fill(int** p, int N, int M) {
    int i, j;
    for(i = 0 ; i < N ; i++)
        for(j = 0 ; j < M ; j++)
            p[i][j] = j;
}

void print(int** p, int N, int M) {
    int i, j;
    for(i = 0 ; i < N ; i++)
        for(j = 0 ; j < M ; j++)
            printf("array[%d][%d] = %d\n", i, j, p[i][j]);
}

void freeArray(int** p, int N) {
    int i;
    for(i = 0 ; i < N ; i++)
        free(p[i]);
    free(p);
}

int main(void)
{
    int **p;
    //getNoReturn(&p, 2, 5);
    p = get(2, 5);
    fill(p ,2, 5);
    print(p, 2, 5);
    freeArray(p ,2);
    return 0;
}

选择最适合您的风格。

关于c - 从 C 中的函数返回多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45397460/

相关文章:

c - 如何计算数组C中的值被使用了多少次?

c - 指针与 c 中的整数二维数组和字符串不同

ios - 将数组保存到 userDefault

c++ - C++ 中的静态函数

python - 用于字符串的 islower() - Python

r - 在 dplyr 中为 group_by 调用变量名称的函数 - 如何在函数中对这个变量进行矢量化?

c - 函数不返回 long long int

c - 时间测量、CPU 滴答声和可调节的 CPU 频率?

javascript - 按一个值对嵌套数组排序,然后按另一个值排序

arrays - 字符串中给定数量的字符的精确匹配