Reserving memory for **

If I have a ** (specifically a int ** in a header file) and I want to reserve memory for it (in a constructor), how would i go about doing it so that the data is not lost when the constructor closes?

Also, how is a multi dimensional array normally set out in memory? is it one long segment holding all sub-arrays or does each sub-array get allocated its own individual memory? If its the former then calloc should do shouldn't it?

Or alternatively, if someone could tell me how to make it so that a local variable's memory does not get released when its function closes then that would be great as I could just do something like

int localVar[x][y];
headerVar = (int**) localVar;

Thanks in advance.
When you declare a static variable like that, it will always be destroyed when the scope closes. If you want it to stay, you must allocate it dynamically.

1
2
3
4
headerVar = new int*[x];
for(size_t i = 0; i < x; ++i) {
    headerVar[i] = new int[y];
}


Make sure you free it similarly when you are finished.

As for layout: there is the initial array of contiguous memory that contains pointers. Each of these pointers points to a separate block of contiguous memory containing data.
Dammit, i should have thought of that.

Thanks
Topic archived. No new replies allowed.