專題:二維數組作為函數參數傳遞

來源:互聯網
上載者:User

#include <stdio.h>
/*********************************
* 方法1: 第一維的長度可以不指定 *
*       但必須指定第二維的長度 *                            
*********************************/
void print_a(int a[][5], int n, int m)    
{
          int i, j;
          
          for(i = 0; i < n; i++)
          {
           for(j = 0; j < m; j++)
             printf("%d ", a[i][j]);
                            
           printf("/n");
          }
}
/*****************************************
*方法2: 指向一個有5個元素一維數組的指標 *
*****************************************/
void print_b(int (*a)[5], int n, int m)        
{
          int i, j;
          
          for(i = 0; i < n; i++)
          {
           for(j = 0; j < m; j++)
             printf("%d ", a[i][j]);                      
   printf("/n");
          }
}/***********************************
*方法3: 利用數組是順序儲存的特性, *
*       通過降維來訪問原數組!*
***********************************/
void print_c(int *a, int n, int m)                          
{
          int i, j;
          
          for(i = 0; i < n; i++)
          {
           for(j = 0; j < m; j++)
             printf("%d ", *(a + i*m + j));   //注意a+i*m+j,m是列號
                            
           printf("/n");
          }
}

int main(void)
{
        int a[4][5] = {{1, 2}, {3, 4, 5}, {6}, {7}};
        
        printf("/n方法1:/n");  
        print_a(a, 4, 5);
        
        printf("/n方法2:/n");  
        print_b(a, 4, 5);  
        
        printf("/n方法3:/n");  
        print_c(&a[0][0], 4, 5);
        
        getchar();
        return 0;
}
~~~~~~~~~~~~~~~~~

這裡需要特別注意幾點:

聲明二維數組int a[4][5].

1、第二種方法中,使用的是指向一維數組的指標作為參數,形式為int (*a)[5].

這裡a指向的地址和int a[4][5]中的a指向的地址值都是相同的。

2、在第三種方法中,傳遞的是二維數組的首元素的地址,所以函數的參數只是一個int型的指標,但是表示某個元素的形式為:*(a+i*m+j) == a[i][j] ,這裡m是列號,不是行號!!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.