从函数返回一个二维数组 [英] Return a 2d array from a function

查看:155
本文介绍了从函数返回一个二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新手到C.
我想从一个函数返回一个二维数组。
它是这样的。

I am a newbie to C. I am trying to return a 2d array from a function. It is something like this

int *MakeGridOfCounts(int Grid[][6])
{
  int cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
  int (*p)[6] = cGrid;
  return (int*)p;
}

我知道这将导致一个错误,需要帮助。谢谢

I know this causes an error, need help. thanks

推荐答案

C语言有一个基本的缺陷:它不可能从函数返回数组。
这有很多解决方法;我将介绍三种。

The C language has a basic flaw: it is impossible to return arrays from functions. There are many workarounds for this; i'll describe three.

返回数组本身的一个指针代替。这导致在C另一个问题:当一个函数返回一个指针的东西,它通常应该动态分配的东西。你不应该忘记释放稍后(当不再需要的数组)。

Return a pointer instead of an array itself. This leads to another problem in C: when a function returns a pointer to something, it should usually allocate the something dynamically. You should not forget to deallocate this later (when the array is not needed anymore).

typedef int (*pointer_to_array)[6][6];

pointer_to_array workaround1()
{
    pointer_to_array result = malloc(sizeof(*result));
    (*result)[0][0] = 0;
    (*result)[1][0] = 0;
    (*result)[2][0] = 0;
    (*result)[3][0] = 0;
    (*result)[4][0] = 0;
    (*result)[5][0] = 0;
    return result;
}

通过指针替换为int

2-D阵列的出现,就像数字的记忆序列,这样你就可以通过一个指向第一个元素替换它。您明确指出要返回数组,但你的例子code返回一个指针为int,所以也许你可以改变你的$ C $其余C.因此。

Replace by a pointer to int

A 2-D array appears just as a sequence of numbers in memory, so you can replace it by a pointer to first element. You clearly stated that you want to return an array, but your example code returns a pointer to int, so maybe you can change the rest of your code accordingly.

int *workaround2()
{
    int temp[6][6] = {{0}}; // initializes a temporary array to zeros
    int *result = malloc(sizeof(int) * 6 * 6); // allocates a one-dimensional array
    memcpy(result, temp, sizeof(int) * 6 * 6); // copies stuff
    return result; // cannot return an array but can return a pointer!
}

具有结构包裹

这听起来很傻,但函数可以返回的结构,即使他们不能返回数组!即使回到结构包含一个数组

Wrap with a structure

It sounds silly, but functions can return structures even though they cannot return arrays! Even if the returned structure contains an array.

struct array_inside
{
    int array[6][6];
};

struct array_inside workaround3()
{
    struct array_inside result = {{{0}}};
    return result;
}

这篇关于从函数返回一个二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆