关于C语言函数返回二维数组的做法

时间:2025-05-09 07:19:37

在C语言中,有时我们需要函数的返回值为一个二维数组。这样外部函数接收到这个返回值之后,可以把接收到的二维数组当成矩阵操作(外部函数不可用普通的一级指针接收返回值,这样的话,外部函数将不知道它具有二维性)。方法如下:

法1.没有使用typedef类型定义

#include <>
int (*fun(int b[][2]))[2]
{
	return b;
}

int main()
{
	int i,j;
	int a[2][2]={1,2,5,6};
	int (*c)[2];
	c = fun(a);
	for(i=0;i<2;i++)
		for(j=0;j<2;j++)
			printf("%d ",c[i][j]);
		return 0;
}
法2.使用typedef类型定义

#include <>
typedef int (*R)[2];
R fun(int b[][2])
{
	return b;
}
int main()
{
	int i,j;
	int a[2][2] = {1,2,5,6};
	R c;
	c = fun(a); 
	for(i=0;i<2;i++)
		for(j=0;j<2;j++)
			printf("%d ",c[i][j]);
	return 0;
}
使用typedef类型定义可以增加程序的可读性
这两种方法本质上是一样的