I'm trying to implement dynamically allocated contiguous 3D arrays in a C code. The arrays must be contiguous because I'm relying on netCDF output of the arrays. Now I adapted a solution posted here Stack OverFlow Solution. This works fine for dynamically allocating the arrays and indexing them...however, when netCDF outputs them there is an offset which appears to scale as the 2nd index size (jcount). Here is the modified function:
void*** newarray(int icount, int jcount, int kcount, int type_size)
{
int i,j,k;
void*** iret = (void***)malloc(icount*sizeof(void***)+icount*jcount*sizeof(void**)+icount*jcount*kcount*type_size);
void** jret = (void**)(iret+icount);
char* kret = (char*)(jret+icount*jcount);
for(i=0;i<icount;i++)
{
iret[i] = &jret[i*jcount];
}
for(i=0;i<icount;i++)
{
for(j=0;j<jcount;j++)
{
jret[i*jcount+j] = &kret[i*jcount*kcount*type_size+j*kcount*type_size];
}
}
return iret;
}
If I understand this function correctly iret is allocated space for the 3D pointers composing iret (first index), the 2D pointers composing jret (2nd index) and the space for the actual values composing kret. The 2D jret pointer is then associated with the 2D array section of iret. Then the same is done for kret. Then every address of iret is pointed to the first value of each section of jret. Then each address of jret is pointed to the first address of kret.
For the record, everything was working fine with preprocessor defined values for my arrays. Also, if I use some printf statements in the code to check the numerics of the arrays they all appear to index correctly and the code runs correctly, it's just the output seems to be the result of non-contiguous memory storage of the arrays.
I have a structure of the form:
typedef struct
{
double ***test;
} STRUCT_TYPE;
Which I then allocate using
mhd = (STRUCT_TYPE *) malloc(sizeof(STRUCT_TYPE));
mhd.test = (double***) newarray(101,7,101,sizeof(double));
This may be an issue with netCDF...but I'd just like to know my allocation routine isn't the issue.