鹿鞭回春胶囊饭前吃:C语言 通过指针从函数返回一个数组

来源:百度文库 编辑:九乡新闻网 时间:2024/04/27 19:30:49

严格的讲,无法直接从函数返回一个数组。但是,可以让函数返回一个指向任何数据结构的指针,当然也可以是一个指向数组的指针。

 

下面直接贴代码:

view plaincopy to clipboardprint?

  1. #include    
  2. #include    
  3. #include    
  4.   
  5. #define PRINT_ADDRESS(addr) printf("0x%08X/n", (addr))   
  6.   
  7. // 使用指针从函数返回一个数组   
  8. // paf是一个函数,它返回一个指针,该指针指向一个包含20个int元素的数组   
  9. int (*paf())[20]  
  10. {  
  11.     int (*pear)[20];  
  12.     int i = 0;  
  13.       
  14.     pear = (int (*)[20])malloc(20 * sizeof(int));  
  15.     printf("Malloc memory, Address: ");  
  16.     PRINT_ADDRESS(pear); // 打印所分配内存的地址   
  17.       
  18.     if (!pear)  
  19.     {  
  20.         printf("malloc failed!/n");  
  21.     }  
  22.   
  23.     // 初始化数据   
  24.     for (i = 0; i < 20; i++)  
  25.     {  
  26.         (*pear)[i] = i;  
  27.     }  
  28.   
  29.     return pear;  
  30. }  
  31.   
  32. void UsePointerReturnArrayFunction()  
  33. {  
  34.     // 声明result是一个指针,指向一个包含20个int元素的数组   
  35.     int (*result)[20];  
  36.       
  37.     char *p = NULL;//"char * test";   
  38.       
  39.     // 上面是变量定义   
  40.     printf("/n使用指针从函数返回一个数组 -->/n");  
  41.       
  42.     // 通过调用函数返回一个指针(指针指向一个数组)   
  43.     result = paf();  
  44.     printf("  Free memory, Address: ");PRINT_ADDRESS(result);  
  45.     free(result); // 打印所释放内存的地址   
  46.       
  47.     printf("%s/n", p);  
  48.       
  49.     printf("--> 使用指针从函数返回一个数组/n/n");  
  50. }  
  51.   
  52. int main()  
  53. {  
  54.     UsePointerReturnArrayFunction();  
  55.       
  56.     return EXIT_SUCCESS;  
  57. }