Why does the following code snippet fails at runtime?
It should work because the memory addresses are contiguous( i even tried by printing memory addresses)
void print(int **mat, int r, int c){
for(int i=0;i<r;++i){
for(int j=0;j<c;++j){
cout << mat[i][j] << " ";
}
cout << endl;
}
}
int main(){
int mat[2][2] = { {1,2}, {3,4} };
print( (int **)mat,2,2);
}
I got itā¦but my question is "since i am collecting the base address of the 2d array in the print function, and then i am accessing the elements using pointer arithmetic and it should work since the elements are consecutiveā¦but why doesnāt it work?? "
When you write
int mat[2][2] = {{1, 2}, {3, 4}};
Note that mat[0]
is a constant pointer, pointing to the address of the element in the first row and first column (i.e., 1).
Similarly, mat[1]
is a constant pointer, pointing to the address of the element in the second row and first column (i.e., 3).
Now, when you write
int ** pointers = (int **) mat
,
the variable pointers
is a āpointer to a pointerā. What happens this way is that the address of the first element in the first row will be assigned to the variable pointers
. And remaining addresses are not assigned.
You can check it using the following code:
#include <bits/stdc++.h>
using namespace std;
void print(int **mat, int r, int c){
cout << mat;
}
int main(){
int mat[2][2] = { {1,2}, {3,4} };
cout << &mat[0][0] << '\n';
cout << mat << '\n';
print( (int **)mat,2,2);
}
// All three cout statements print the same hex value
Now that other addresses are not known to the variable pointers
, it will result in an \color{red}\text{RTE}.
1 Like
/*to be honest i tried the same problem and wasted hoursš. i guess the programm will work if converted in c languageā¦but here is an alternative
#include
using namespace std;
void print(int mat, int r, int c){
for(int i=0;i<rc;++i){
cout << *(mat+i) << " ";
if(i+1==r)
cout<<endl;
};
}
int main(){
int mat[2][2] = { 1,2,
3,4 };
/* int **p;
p=(int **)mat;
cout<<p<<endl;
cout<<++p<<endl;*/
print(mat[0],2,2);
}
Correct me if i am wrong,
let say the base address of matrix is 2000, then
&mat[0][0] = 2000
&mat[0][1] = 2004
&mat[1][0] = 2008
&mat[1][1] = 2012
Now when we access mat[i][j] in main method, it is equivalent to saying * ( *(mat+i) + j) , where
mat+i points to ith array in matrix as type of mat is int ( * )[2]. (mat+1 will be pointing to address 2008)
Now when we try to access mat[i][j] in print function, *( *(mat+i) + j) will not yield mat[i][j] since the base type of mat is int ** , mat+i will no longer point to ith array.
(In this case, mat+1 will be pointing to 2004)
This is right, isnāt it?