在这个返回语句中
return array;
数组指示符array 被转换为指向它的第一个int ( * )[10] 类型元素的指针。但是函数返回类型是int **。没有从 int ( * )[10] 类型到 int ** 类型的隐式转换。所以编译器会报错。
注意函数的使用者需要知道数组的大小。
所以我建议你像这样声明函数
static int ( *function( void ) )[5][10]
{
static int array[5][10];
return &array;
}
然后在 main 你可以写
int ( *test )[5][10] = function();
解引用指针test,您将获得数组。
这是一个演示程序。
#include <stdio.h>
enum { M = 5, N = 10 };
static int ( *function( void ) )[M][N]
{
static int array[M][N] =
{
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 },
{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 },
{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 },
{ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }
};
return &array;
}
int main(void)
{
int ( *test )[M][N] = function();
printf( "The size of the array is %zu\n", sizeof( *test ) );
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
printf( "%d ", ( *test )[i][j] );
}
putchar( '\n' );
}
return 0;
}
程序输出是
The size of the array is 200
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5
您可以通过以下方式为数组类型引入别名,以使函数声明更简单
#include <stdio.h>
enum { M = 5, N = 10 };
typedef int Array[M][N];
static Array * function( void )
{
static Array array =
{
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 },
{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 },
{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 },
{ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }
};
return &array;
}
int main(void)
{
Array *test = function();
printf( "The size of the array is %zu\n", sizeof( *test ) );
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
printf( "%d ", ( *test )[i][j] );
}
putchar( '\n' );
}
return 0;
}