0

I have a 2D array and I am trying to assign the 1st dimension of that 2D array to a pointer like below but that doesn't work.

fixed (byte* fixedInput = array2D[0])

How can I assign only the first dimension like I am trying to do to fixedInput?

fixedInput will then be a 1 dimensional pointer array with all info from the 1st dimension of array2D

Thank you!

    unsafe static void testFunction()
    {
        byte[,] array2D = new byte[10, 100];

        fixed (byte* fixedInput = array2D[0])
        {
        }
    }
Andreas
  • 1,121
  • 4
  • 17
  • 34

1 Answers1

0

You cannot. It is a pointer into memory. The data of a 2D array is arranged in the way that the last dimension is in a sequence, in locations direclty behind eachother.

When you get a pointer, you are following the memory the way it is filled in.

If you want to read data along the other dimension, you'll need to step with strides, skipping each line.

public unsafe static void testFunction()
{
    uint[,] array2D = new uint[10, 100];
    for(int x=0;x<100;x++)
    {
        for(int y=0;y<10;y++)
            array2D[y,x] = (uint)(1000u*y+x);
    }

    // read some data along first dimension.
    fixed (uint* fixedInput = &array2D[1,90])
    {
        for(int j=0;j<5;j++)
            System.Console.WriteLine(string.Format("{0}",fixedInput[j*100]));
}

The data from the sample-array is arranged in memory this way:

0   1   2   3   4 [...] 99  1000  1001  1002 [...]
Blindleistung
  • 672
  • 8
  • 21