0

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?

leeway00
  • 87
  • 1
  • 1
  • 6
  • 1
    Your code is UB. You access/set at `(&a)[1]`. This memory that isn't reserved for anything. – ALX23z Apr 05 '23 at 04:07
  • 1
    Side note : Why are you still using "C" style arrays? Passing pointers + sizes seperately is bound to result in bugs later. Have a look at `std::vector>`. In current C++ you should [avoid the use of naked new/delete as much as possible](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#r11-avoid-calling-new-and-delete-explicitly). – Pepijn Kramer Apr 05 '23 at 04:22

1 Answers1

0
int main(){
    double *a;
    allocation(&a, 3, 3);

In t he above quoted snippet, a doesn't point to valid memory, so when you pass it into allocation, undefined behavior occurs.

You can avoid this by actually allocating memory for a.

int main(){
    double a[3][3];
    allocation(&a, 3, 3);
Chris
  • 26,361
  • 5
  • 21
  • 42