I'm working with 3D and 4D arrays of variable sizes and they have to be continuous (sometimes is easier call as *(&x[0][0][0] + k) than the 'x[][][]' way). 'Cause of the variable size of the array, I need to allocate dynamically. I found this code, in another answer (Dynamic memory allocation for 3D array) to do that and it works fine, but I don't know how much memory use of the stack.
double ***arr3dAlloc(const int ind1, const int ind2, const int ind3) {
int i;
int j;
double ***array = (double***)malloc((ind1 * sizeof(double*)) +
(ind1 * ind2 * sizeof(double**)) +
(ind1 * ind2 * ind3 * sizeof(double)));
for (i = 0; i < ind1; ++i) {
array[i] = (double**)(array + ind1) + i * ind2;
for (j = 0; j < ind2; ++j) {
array[i][j] = (double*)(array + ind1 + ind1 * ind2) + i * ind2 * ind3 + j * ind3;
}
}
return array;
}
the question is:
What is the difference between
double ***arr1 = arr3dAlloc(N1,N2,N3);anddouble arr2[N1][N2][N3];Given that
arr2usesN1*N2*N3*sizeof(double)memory of the stack, how much memory doesarr1use? Onlysizeof(double***)?- In general, is there a method to measure the use of stack memory of any variable?
population[J][K][N]where the J and K index represent the cells of a spatial grid and N is for the population number of the cell i,j. The brute part of the code use pointers to the first element and make some computations, but some of functions to computate must be easily editable and readable so i would like to use the population[i][j][n] notation. I need to run several simulation with the same scheme but differents 'special functions' so stopping all the time to think 'in what place of memory am i' is not optimaldouble ***is not an array or even a similar data structure! A pointer is not an array. And tp pointers don't make a 2D array, 3 not an 3D array. Why not use a true array if you need one? The wild casts already should make you suspisious. You don't even allocate the correct memory.