I have a question about Jagged arrays in C#, as i read about Jagged arrays somewhere on the internet, i think that the memory allocation of 2d Jagged arrays in C# is the same as memory allocation of 2d arrays in C++, because a 2d Jagged array has an array of pointer that each pointer refers to an array of elements (for example integer elements) i mean that memory allocation of the array bellow in C++ :
int** twoDArr {new int* [number1]};
for (int i = 0; i < number1; i++)
{
twoDArr[i] = new int[number2];
}
is the same as memory allocation of 2d Jagged arrays in C# :
int[][] 2DJaggedArray = new int[number1][];
for (int i = 0; i < 2DJaggedArray.GetLength(0); i++)
{
2DJagggedArray[i] = new int[number2];
}
But i am not sure about , So could you please tell me if i am right and if so, could you please explain me how is memory allocation of 2d array in C# for example array bellow:
int[,] 2DArray = new int[number1,number2];
Thanks.
Yes you are right. A Jagged array in C# is basically an single dimension array in memory where each element is just an reference. When you initialize the array in the for
loop, it creates a new array somewhere else in memory and the reference points to it.
In case of multidimensional arrays ([,]
), the situation is very different. When you initialize such array, a single block of memory is created and it's size is equal to the product of all dimensions of the array. Technically having a multidimensional array of size [M,N]
is represented in memory the same way as a simple array of size [M * N]
. The access by multiple indices is basically just a syntactic sugar where the framework calculates the actual position of the element by multiplication of the dimensions.