编程基础-------C语言函数返回二维数组的做法

来源:互联网 发布:tts软件怎么用 编辑:程序博客网 时间:2024/05/16 05:12

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

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

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

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