Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is C# analog for C's two-dimensional array access like that: palette[ val & 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

like image 395
Kosmo零 Avatar asked Dec 14 '25 20:12

Kosmo零


2 Answers

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

like image 104
Tomas Kubes Avatar answered Dec 17 '25 09:12

Tomas Kubes


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].

like image 30
Maximilian Gerhardt Avatar answered Dec 17 '25 10:12

Maximilian Gerhardt



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!