I am trying to make a matrix through an array of addresses pointing to the other arrays. When I execute the below code, I have a result I cannot understand.
The address printed out from allocation
and a for loop in main
are same. However, get_address
prints out the different address, even though it is doing exactly the same with the for loop in main
.
void allocation(double **a, int rows, int columns){
for (int i=0; i<rows; i++){
a[i] = new double[columns];
}
for (int i=0; i<rows; i++){
cout << a[i] << " ";
}
cout << endl;
}
void get_address(double *a, int rows, int columns){
for (int i=0; i<rows; i++){
cout << (&a)[i] << " ";
}
cout << endl;
}
int main(){
double *a;
allocation(&a, 3, 3);
get_address(a, 3, 3);
for (int i=0; i<3; i++){
cout << (&a)[i] << " ";
}
cout << endl;
return 0;
}
0x100106220 0x100106240 0x100106a50
0x100106220 0x16fdfdcd0 0x1000031dc # this is different
0x100106220 0x100106240 0x100106a50
Why am I getting different addresses? Also, when I trying to assign numbers on a
as
void assign_number(double *a, int rows, int columns){
double **ptr = &a;
for (int i=1; i<rows; i++){
for (int j=0; j<columns; j++){
ptr[i][j] = 1
}
}
}
This generates EXC_BAD_ACCESS (code=1, address=0x0)
error. Why accessing is problematic with this way?