views:

29

answers:

1

Hi, 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

+1  A: 

I'm not entirely sure that casting your int * will have the effect you desire.

After your initial statement, x points into your newly-allocated memory, so it's fine to do things like x[1] = 8;. The memory holds your data (i.e., the values of your array).

However, after your second statement, y thinks it's pointing to an int *, effectively turning your former data into a set of int pointers. 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: http://stackoverflow.com/questions/365782/how-do-i-best-handle-dynamic-multi-dimensional-arrays-in-c-c

Lawrence Velázquez
i admit my question was entirely lame. you are right to say that the array contains not only my data but also the pointers to each row.
bliako