3

There is such array defined in C code: u8 palette[4][4];

Later some element accessed like that: palette[ val & 3 ]

In C code it's used like that: memcpy(dest3+12, palette[ val & 3 ], 4);

I don't understand what element is accessed via this code. I tried to do same in C#, but it tells me Wrong number of indices inside []; exptected 2

Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148
Kosmo零
  • 4,001
  • 9
  • 45
  • 88

3 Answers3

4

In C you can point to particular row in array, because C array is just sequence of items. Two subsequent arrays are just sequence of items again and that is why it is possible to access sub-array in C. That is why, you cannot get the size in array in C just from array pointer.

In C#, there are two types of "multidimensional" arrays: Multidimensional arrays and Jagged Arrays.

Classic multi-dimensional cannot be access just by sub-index because array in C# is not just a sequence of items, but there is also a header in which contain size of array, type pointer and sync block. Two subsequent C# arrays will contains a header inside and it will not fulfill C# array format.

Jagged array is array of arrays and you can access sub-array with only sub-index in similar way to C#.

Equivalent code in C# would be:

byte[][] palette = new byte[4][];

for (int i = 0; i < palette.Length; i++)
{
   palette[i] = new byte[4];
}

byte[] destination = new byte[4];

int val = 1;
Array.Copy(palette[val & 3], 0, destination, 12, 4);

Be aware that in memcpy are parameters in order: destination, source whereas in Array.Copy are parameters in reverse order: source, destination

Community
  • 1
  • 1
Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148
2

In C, palette would just be a pointer, dereferencable at any time. pallete[i] is valid in C even for u8 palette[4][4];. However, when you declare byte[,] palette = new byte[4,4]; in C#, you must properly use two indices to access the array. You might want to declare your palette in C# as a flattened-out array byte[] palette = new byte[4*4]and for pallete[x,y] write palette[y*4 + x].

Maximilian Gerhardt
  • 5,188
  • 3
  • 28
  • 61
1

palette is a square matix 4x4.

Using val & 3 you are considering only first 2 bit of val variable value: that means you are accessing as max index 0x03.

Whatever value has val only first 2 bits are taken into account.

Eg if val is 8 bit wise:

    val
0b11111100 & 3 = 0b00000000
0b11111101 & 3 = 0b00000001
0b11111110 & 3 = 0b00000010
0b11111111 & 3 = 0b00000011

Your code is accessing the array row by row.

LPs
  • 16,045
  • 8
  • 30
  • 61
  • 1
    Thank you for explaining this, but I didn't understand another thing. How it were possible that two-dimensional array were accessed by single index. What index exactly were accessed like that. But `Maximilian Gerhardt` explained me this. – Kosmo零 Apr 29 '16 at 14:17