Returning two-dimensional array in C function? [duplicate]

落花浮王杯 提交于 2019-12-25 18:37:45

问题


I have looked for this for quite sometime but haven't found a satisfactory solution. How do I return a double dimensional array in a C function?

float **KE()
{
    float K[2][2]={{1,2},{3,4}};
    return K;
}

For the above code, I get the error

error: cannot convert 'float<*>[2]' to 'float**' in return

回答1:


Put it in a struct:

struct dar { float data[2][2]; };

struct dar K()
{
    struct dar x = { { { 1, 2 }, { 3, 4 } } };
    return x;
}

Usage:

struct dar x = K();

printf("%f %f\n", x.data[0][0] + x.data[0][1], x.data[1][0] + x.data[1][1]);



回答2:


You can't return an array from a function. Arrays are not copyable. You can wrap it into a struct, but in general case passing around a potentially large object by value is not a good idea.

What you can do is return a pointer to an array from function. But for that you have to make sure the object that pointer points to continues to live when the function exits. A popular idiom is to pass the destination array from the caller code and fill it inside the function

float (*KE)(float (*dst)[2][2])[2][2]
{
  (*dst)[0][0] = 1;
  (*dst)[0][1] = 2;
  (*dst)[1][0] = 3;
  (*dst)[1][1] = 4;
  return dst;
}

...
float array[2][2];
KE(&array);

Note that in this case it is not necessary to return the pointer to the array from the function, since the resultant array is already known to the caller. But I did it anyway to further complicate the function declaration syntax and make it more difficult to read.

You can always de-obfuscate it by defining a typedef name for the array type

typedef float F22[2][2];

F22* KE(F22* dst)
{
  ...
}

Alternatively, to preserve the neatness of the aggregate initialization syntax, you can implement the function body as

F22* KE(F22* dst)
{
  const F22 K = { {1, 2}, {3, 4} };
  memcpy(dst, &K, sizeof *dst);
  return dst;
}

or even as

F22* KE(F22* dst)
{
  return memcpy(dst, &(const F22) { {1, 2}, {3, 4} }, sizeof *dst);
}


来源:https://stackoverflow.com/questions/17497057/returning-two-dimensional-array-in-c-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!