Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a 3D array type to a 1D array type in C#?

Tags:

arrays

c#

For example, I have a 3D array

float[,,] a3d;

And it is initialized with some elements. How can I change it to 1D array but without doing any copies (using the same data in the heap).

float[] a1d;
a1d = ???

Using unsafe mode pointers is fine.

like image 583
user1899020 Avatar asked Dec 06 '25 21:12

user1899020


1 Answers

If you're willing to use unsafe, you can access the multi-dimensional array in linear order as a float*.

For example, this code:

        var b = new float[2, 3, 4];

        fixed (float* pb = &b[0,0,0])
        {
            float* p = pb;
            for (int i = 0; i < 2*3*4; i++)
            {
                *p = i + 1;
                p++;
            }
        }

This will initialize the array to sequential values. The values are stored in 'depth-first' ordering, so b[0, 0, 0], b[0, 0, 1], b[0, 0, 2], b[0, 0, 3], b[0, 1, 0], b[0, 1, 1], etc.

This does not, however, allow you to keep that pointer around or somehow 'cast it back' to a 1d managed array. This limited scope of fixed pointer blocks is a very deliberate limitation of the managed runtime.

like image 194
Dan Bryant Avatar answered Dec 09 '25 14:12

Dan Bryant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!