# 将指针返回数组的函数

``````#include <stdio.h>
#include <stdlib.h>

int (*foo(size_t row, size_t col))[3];

int main(void){
size_t row, col;

printf("Give the ROW: ");
if ( scanf("%zu",&row) != 1){
printf("Error, scanf ROW\n");
exit(1);
}

printf("Give the COL: ");
if ( scanf("%zu",&col) != 1){
printf("Error, scanf COL\n");
exit(2);
}

int (*arr)[col] = foo(row, col);

for ( size_t i = 0; i < row; i++){
for( size_t j = 0; j < col; j++){
printf("%d ",*(*(arr+i)+j));
}
}

free(arr);
}

int (*foo(size_t row, size_t col))[3]{
int (*arr)[col] = malloc(row * col * sizeof(int));
int l=0;

if (arr == NULL){
printf("Error, malloc\n");
exit(3);
}

for ( size_t i = 0; i < row; i++){
for( size_t j = 0; j < col; j++){
*(*(arr+i)+j) = l;
l++;
}
}

return arr;
}
``````

``````Give the ROW: 2
Give the COL: 5
0 1 2 3 4 5 6 7 8 9
``````

``````int (*foo(size_t row, size_t col))[3]{ /* code */ }
``````

1）这`int (*foo(size_t row, size_t col))[SIZE]`可能吗，必须将SIZE作为参数？还是我应该以其他方式声明此功能？

2）这是我在这里尝试过的正确方法，还是有另一种选择？

@ChronoKitsune说我应该使用/尝试`[]`（未指定大小的数组），在这种情况下，功能将变成这样：

``````int (*foo(size_t row, size_t col))[]{ /* code */ }
``````

``````int foo[3];
``````

``````int (foo)[3];
``````

``````int (*foo)[3];
``````

``````int (*foo(size_t row, size_t col))[3];
``````

（6.7.6.2/2）

``````int *foo(size_t row, size_t col);
``````

``````int (*bar(size_t row, size_t col))[];
``````

，但是您会发现几乎在每种方式中都很难使用该返回类型。例如，声明可以保存返回值的变量比较棘手和丑陋：

``````int (*array_ptr)[] = bar(x, y);
``````

``````int z = (*array_ptr)[1];
``````

``````int *ptr = foo(x, y);
int w = ptr[2];
``````

0条评论