开发者

Interpreting linear memory space as 1D,2D,...,ND efficiently in C

开发者 https://www.devze.com 2023-01-10 01:15 出处:网络
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.

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 segm开发者_开发技巧ent 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, 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: How do I best handle dynamic multi-dimensional arrays in C/C++?


This will do the trick, note that d2 does not need to be known at compile time.

int *y[d2];
y=(int (*)[d2])x;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号