I would like to understand how does it works to scan a dynamically allocated two-dimensional array using pointers arithmetics?
Here is my implementation, but the behaviour is unclear.
#include <iostream>
using namespace std;
void init_matrix(int ** m, int size);
void print_matrix(int ** m, int size);
void print_matrix_pointers(int ** m, int size);
int main (){
srand (time(NULL));
int size = 3;
int ** dynamic_matrix = new int * [size];
for (int i = 0; i < 10; i ) {
dynamic_matrix[i] = new int [size];
}
init_matrix(dynamic_matrix, size);
cout << "Dynamic matrix accessed using square brackets ([i][j]): " << endl;
print_matrix(dynamic_matrix, size);
cout << "Dynamic matrix accessed using pointers arithmetics: " << endl;
print_matrix_pointers(dynamic_matrix, size);
return 0;
}
void init_matrix(int ** m, int size) {
for (int i = 0; i < size; i ){
for (int j = 0; j < size; j ){
m[i][j] = rand();
}
}
}
void print_matrix(int ** m, int size){
for (int i = 0; i < size; i ){
for (int j = 0; j < size; j ){
cout << m[i][j] << " ";
}
cout << endl;
}
}
void print_matrix_pointers(int ** m, int size){
for (int i = 0; i < size; i ){
for (int j = 0; j < size; j ){
cout << *(*m (i * size) j) << " "; //
}
cout << endl;
}
cout << endl;
}
For instance if size was 3 I would get this output.
Dynamic matrix accessed using square brackets ([i][j]):
3 3 4
9 5 9
4 9 4
Dynamic matrix accessed using pointers arithmetics:
3 3 4
32735 9 5
9 32735 4
CodePudding user response:
With *(*m (i * size) j) you treat m as a contiguous array of values, which it isn't. It's more like a jagged array. You need to treat it like the array of pointers it really is, like *(*(m i) j).
CodePudding user response:
Two typos in your code:
int size = 3;
int ** dynamic_matrix = new int * [size];
for (int i = 0; i < 10; i ) {
dynamic_matrix[i] = new int [size];
}
size is 3 but you write 10 elements. That is undefined behavior.
Then you are advancing the pointer wrongly.
void print_matrix_pointers(int ** m, int size){
for (int i = 0; i < size; i ){
for (int j = 0; j < size; j ){
cout << *( *(m i) j) << " "; //
}
cout << endl;
}
cout << endl;
}
m points to an array of pointers to int. You have to increment m by i to get to the i-th row. Then you want to access the jth element of the array pointed to by m[i], hence you have to first dereference m i then add j to get the address of jth element.
