3

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.

5
  • What do you mean without doing any copies? Commented Jun 5, 2016 at 23:48
  • @EvanTrimboli Means allocating no data in the heap by the 1D array. Commented Jun 5, 2016 at 23:49
  • c# is a managed framework language, you are really over-thinking your problem if you start trying to worry about what is going on in the stack heap. beyond that, it's not really obvious what you want your result to be, since 3d arrays and 1d arrays aren't really represented the same way..... Commented Jun 6, 2016 at 0:03
  • I think you're saying you want to just cast the variable. You can't do that. C# is not C++. Maybe you can have an access method that you use to pass in a single index value and it returns the appropriate member? Commented Jun 6, 2016 at 0:06
  • 1
    Option 2: invert the problem. Store everything in a 1d array, and add a wrapper for the ability to access elements using 3 indices. Commented Jun 6, 2016 at 0:10

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.