1. 程式人生 > >向函數中傳輸二維數組

向函數中傳輸二維數組

word 我們 clas ams end out for bsp 尋址


void xxx (int **a, int r . int c){  // r代表行 , c代表列

  //在轉變後的函數中,array[i][j]這樣的式子是不對的,因為編譯器不能正確的為它尋址,所以我們需要模仿編譯器的行為把array[i][j]這樣的式子手工轉變為

*( (int*) a + c* (i) + (j) );

}

int a[3][3] =
{
{1, 1, 1},
{2, 2, 2},
{3, 3, 3}
};

xxx( (int **)a , 3 ,3 ) ; //強制轉換並調用函數

例子 : 打印輸出二維數組函數

#include <iostream>
using namespace std;

void print_array ( int**a , int r , int c ) {

  for (int i = 0; i < r; i++)
  {
    for ( int j = 0 ; j<c ; j++)
      {
        cout << *((int*) a + c* (i) + (j)) ;
        if(j == c-1 ) cout <<endl;
      }
  }
}

int a[3][3] =
{
  {1, 1, 1},
  {2, 2, 2},
  {3, 3, 3}
};

int main(){

print_array ((int **) a ,3,3);

}

向函數中傳輸二維數組