Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

c - Return a 2d array from a function

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Replace by a pointer to an array

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...