2008年9月25日木曜日

配列とポインタ(配列の受け渡し)

プログラム
*********************
int
main()
{
const int ROW = 4; //行の次元
const int COL = 5; //列の次元

int mat[][COL] = { {11,12,13,14,15},
{21,22,23,24,25},
{31,32,33,34,35},
{41,42,43,44,45} };

    cout << "もとの行列 mat[4][5]:2元配列(配列の配列)\n";
cout << "サイズ: " << sizeof(mat) << endl;
int i,j;
for(i = 0; i < ROW; i++){
for(j = 0; j < COL; j++)
cout << " " << mat[i][j];
cout << endl; //行の終わりに改行
}

// 配列へのポインタ
int (*ptr1)[COL];
ptr1 = &mat[0]; //行列の先頭アドレスで初期化



cout << "\nポインタ (*ptr1)[5]:配列へのポインタ\n";
cout << "ポインタのサイズ: sizeof(ptr1) = "
<< sizeof(ptr1) << endl;
cout << "ポインタが指しているサイズ: sizeof(*ptr1) = "
<< sizeof(*ptr1) << endl;
for(i = 0; i < ROW; i++){
for(j = 0; j < COL; j++)
cout << " " << ptr1[i][j];
cout << endl; //行の終わりに改行
}


実行結果
*********************************
もとの行列 mat[4][5]:2元配列(配列の配列)        
サイズ: 80
11 12 13 14 15
21 22 23 24 25
31 32 33 34 35
41 42 43 44 45

ポインタ (*ptr1)[5]:配列へのポインタ
ポインタのサイズ: sizeof(ptr1) = 4
ポインタが指しているサイズ: sizeof(*ptr1) = 20
11 12 13 14 15
21 22 23 24 25
31 32 33 34 35
41 42 43 44 45


○もう一つの渡し方
プログラム
*********************
int main()
{
const int ROW = 4; //行の次元
const int COL = 5; //列の次元

int mat[][COL] = { {11,12,13,14,15},
{21,22,23,24,25},
{31,32,33,34,35},
{41,42,43,44,45} };


int *ptr;
ptr = &mat[0][0]; //先頭要素のアドレスで初期化

for(int i = 0; i < ROW; i++){
for(int j = 0; j < COL; j++)
cout << " " << ptr[ i * COL + j];
cout << endl; //行の終わりに改行
}

return 0;
}

実行結果
***********************************
 11 12 13 14 15                  
21 22 23 24 25
31 32 33 34 35
41 42 43 44 45



0 件のコメント: