I would like to understand how does it works to scan a dynamically allocated two-dimensional array using pointers arithmetics?
I can't figurate why in my example pointer arithmetic isn't returning the same results as using array indexing.
Here is my implementation:
#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()%10;
}
}
}
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 array indexing ([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
int size = 3;butfor (int i = 0; i < 10; i++) {thats undefined behavior. Output of the code could be anything.std::vectorand appropriate functions and statements (like rangeforloops), you can avoid many problems.