如果数组是静态分配的,或者如果它是通过malloc()
et al 动态分配的,则可以返回指向数组开头的指针。
int *function1(void)
{
static int a[2] = { -1, +1 };
return a;
}
static int b[2] = { -1, +1 };
int *function2(void)
{
return b;
}
/* The caller must free the pointer returned by function3() */
int *function3(void)
{
int *c = malloc(2 * sizeof(*c));
c[0] = -1;
c[1] = +1;
return c;
}
或者,如果您喜欢冒险,您可以返回一个指向数组的指针:
/* The caller must free the pointer returned by function4() */
int (*function4(void))[2]
{
int (*d)[2] = malloc(sizeof(*d));
(*d)[0] = -1;
(*d)[1] = +1;
return d;
}
小心那个函数声明!完全改变其含义并不需要太多改变:
int (*function4(void))[2]; // Function returning pointer to array of two int
int (*function5[2])(void); // Array of two pointers to functions returning int
int (*function6(void)[2]); // Illegal: function returning array of two pointers to int
int *function7(void)[2]; // Illegal: function returning array of two pointers to int