Is it possible to allocate a 1D memory space
int *x=(int *)malloc(100*sizeof(int));
and then recast the returned pointer to 2D array e.g.
int **y=(int **)x;
and access it as if it was 2D array e.g. y[1][2] = 12;?
My aim is to take a shared memory segment and return 1D,2D,…ND array depending how the user wants to interpret this linear space with maximum efficiency (i.e. without declaring a new N-Dimensional array and copy data into it).
On a second note, is there a library for C which handles N-dimensional arrays, getting slices from them and transposing them efficiently (e.g. converting row-major to col-major)?
thanks,
bliako
I’m not entirely sure that casting your
int *will have the effect you desire.After your initial statement,
xpoints into your newly-allocated memory, so it’s fine to do things likex[1] = 8;. The memory holds your data (i.e., the values of your array).However, after your second statement,
ythinks it’s pointing to anint *, effectively turning your former data into a set ofintpointers. All the values you had stored before are now being treated as addresses to other locations in memory. You are not simply redefining how you address the memory you allocated earlier; you are completely repurposing the memory.I don’t think it’s impossible to do what you suggest, but it’s not as easy as the method you offered.
As for a library for handling multidimensional arrays, check out this post: How do I best handle dynamic multi-dimensional arrays in C/C++?