2007-08-12

Passing Multidimensional Arrays


#include <iostream>
using std::cout;

void print_m35(int m[3][5]);
void print_mi5(int m[][5], int dim1);
//void print_mij_(int m[][], int dim1, int dim2);
void print_mij(int* m, int dim1, int dim2);


void print_m35(int m[3][5])
{
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) cout << m[i][j] << '\t';
cout << '\n';
}
}

void print_mi5(int m[][5], int dim1)
{
for (int i = 0; i < dim1; i++)
for (int j = 0; j < 5; j++) cout << m[i][j] << '\t';
cout << '\n';

}

/*
void print_mij_(int m[][], int dim1, int dim2)
{
for (int i = 0; i < dim1; i++) {
for (int j = 0; j < dim2; j++) cout << [i][j] << '\t';
cout << '\n';
}
}
*/

void print_mij(int* m, int dim1, int dim2)
{
for (int i = 0; i < dim1; i++) {
for (int j = 0; j < dim2; j++) cout << m[i * dim2 + j] << '\t';
cout << '\n';
}
}

int main()
{
int v[3][5];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
v[i][j] = j;

print_m35(v);
print_mi5(v, 3);
print_mij(&v[0][0], 3, 5);

return 0;
}

沒有留言: