user1899020
user1899020

Reputation: 13575

How to convert a 3D array type to a 1D array type in 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.

Upvotes: 3

Views: 269

Answers (2)

Dan Bryant
Dan Bryant

Reputation: 27495

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.

Upvotes: 2

Alexander Petrov
Alexander Petrov

Reputation: 14231

You can get values from array of any dimension by an enumerating:

float[,,] a3d = new float[2, 2, 2] {
    { { 1f, 2f }, { 3f, 4f } },
    { { 5f, 6f }, { 7f, 8f } }
};

foreach (float f in a3d)
    Console.Write(f + " ");

Output:

1 2 3 4 5 6 7 8

Set in this way is impossible, afaik.

Upvotes: 0

Related Questions