[C++]二维数组还是一维数组？

2014-09-24

1 // Create
2 int *m = new int[n_row * n_col];
3
4 // Free
5 delete [] m;

1 // Create
2 int **m = new int*[n_row];
3 for ( int i = 0; i < n_row; ++i )
4 m[i] = new int[n_col];
5
6 // Free
7 for ( int i = 0; i < n_row; ++i )
8 delete [] m[i];
9 delete [] m;

1 for ( int i = 0; i < n_row; ++i )
2 {
3 for ( int j = 0; j < n_col; ++j )
4 {
5 matrix[i * n_col + j] = answer;
7 }
8 }

1 for ( int j = 0; j < n_col; ++j )
2 {
3 for ( int i = 0; i < n_row; ++i )
4 {
5 matrix[i * n_col + j] = answer;
7 }
8 }

1 for ( int i = 0; i < n_row; ++i )
2 {
3 for ( int j = 0; j < n_col; ++j )
4 {
5 int row = i * 7 % n_row;
6 int col = j * 11 % n_col;
7 matrix[i * n_col + j] = answer;
9 }
10 }

1 matrix[i * n_col + j] = answer;

1 ; matrix[i * n_col + j] = answer;
2 mov edx, DWORD PTR _i\$3[ebp]
3 imul edx, DWORD PTR _n_col\$[ebp]
4 add edx, DWORD PTR _j\$2[ebp]
5 mov eax, DWORD PTR _matrix\$[ebp]
6 mov ecx, DWORD PTR _answer\$[ebp]
7 mov DWORD PTR [eax+edx*4], ecx

2 mov ecx, DWORD PTR _i\$4[ebp]
3 mov edx, DWORD PTR _matrix\$[ebp]
4 mov eax, DWORD PTR [edx+ecx*4]
5 mov ecx, DWORD PTR _j\$3[ebp]
6 mov edx, DWORD PTR _answer\$[ebp]
7 mov DWORD PTR [eax+ecx*4], edx

1 // Create
2 int **m = new int*[n_row];
3 int *block = new int[n_row * n_col];
4 for ( int i = 0; i < n_row; ++i )
5 m[i] = &block[i * n_col];
6 return m;