C`函数的返回值为一个二维数组

来源:互联网 发布:淘宝手机店铺怎么装修视频 编辑:程序博客网 时间:2024/05/16 11:31

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

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

[cpp] view plaincopyprint?
  1. #include <stdio.h> 
  2. int (*fun(int b[][2]))[2] 
  3.     return b; 
  4.  
  5. int main() 
  6.     int i,j; 
  7.     int a[2][2]={1,2,5,6}; 
  8.     int (*c)[2]; 
  9.     c = fun(a); 
  10.     for(i=0;i<2;i++) 
  11.         for(j=0;j<2;j++) 
  12.             printf("%d ",c[i][j]); 
  13.         return 0; 
法2.使用typedef类型定义

[cpp] view plaincopyprint?
  1. #include <stdio.h> 
  2. typedefint (*R)[2]; 
  3. R fun(int b[][2]) 
  4.     return b; 
  5. int main() 
  6.     int i,j; 
  7.     int a[2][2] = {1,2,5,6}; 
  8.     R c; 
  9.     c = fun(a);  
  10.     for(i=0;i<2;i++) 
  11.         for(j=0;j<2;j++) 
  12.             printf("%d ",c[i][j]); 
  13.     return 0; 
使用typedef类型定义可以增加程序的可读性
这两种方法本质上是一样的