c cannot directly return an array defined within a function
Can return global array, static array, array passed in by function parameters, malloc memory
But I think it is most practical to pass parameters into an array and then return this array.
No matter the return is one-dimensional, two-dimensional, or even multi-dimensional. The return value is the first address of the array, so the return value must be converted to the corresponding dimension and array type to correctly read the data.
#include "TY.h"
int r[3]; //static 也可以
static int w[2][3];
int main(void) {
//----------------------------------------------
int in[3];
int * b(int *q) {
int a[3]={1,2,3};
memcpy(q,a,12);
return q; //返回输入的一维数组
}
printf("i1:%d\n",b(in)[0]);
//----------------------------------------------
int o2[2][3];
int **b3(int (*i)[3]){ //输入如是 int **i, 则编译报警,因为此类型和o2[2][3]的int (*)[3]不同
int a1[2][3]={
{14,24,34},{41,51,61}};
memcpy(i,a1,24);
int **zz=(int **)i; //因为函数返回类型为 int ** 类型,把int (*)[3]i 转为 int ** zz类型,不转换也可以用,但编译报警
return zz; //返回输入的二维数组
}
int (*p2)[3]=(int (*)[3])b3(o2);
printf("i2:%d\n",p2[0][1]);
//----------------------------------------------------
int *b4(void){
int a4[3]={11,22,33};
memcpy(r,a4,12);
return r; //返回全局或static 一维数组
}
printf("s1:%d\n",b4()[2]);
//----------------------------------------------------
int (*b1())[3] { //这种函数定义形式很奇怪,但是正确的 **b1() 也可以用,但编译报警
int a[2][3]={
{14,24,34},{41,51,61}};
memcpy(w,a,24);
return w; //返回全局或static 二维数组
}
int (*p3)[3]=b1();
printf("s2:%d\n",p3[0][1]);
//-------------------------------------------------------
int *c=malloc(3*sizeof(int));
int *b2() {
int a[3]={11,21,31};
memcpy(c,a,12);
return c; //返回malloc 一维数组
}
printf("malloc1:%d\n",b2(in)[2]);
free(c);
//-----------------------------------------------------
int **c5=(int **)malloc(24*sizeof(int));
int **b5() {
int a5[2][3]={
{11,21,31},{80,81,82}};
memcpy(c5,a5,24);
return c5; //返回malloc 二维数组
}
int (*p5)[3]=(int (*)[3])b5();
printf("malloc2:%d\n",p5[0][1]);
free(c5);
return 0;
}