c# int[,] vs int[][]

 

int[,] is used to declare a multi-dimension array of x,y equal equal multi-dimensional array of int in this case. Due to its fixed size, it is often stored as a continuous memory location

For example, 

 int[,] matrix = {
     { 0, 0, 0, 1 },
     { 0, 1, 0, 0 },
     { 0, 0, 1, 0 },
     { 1, 0, 0, 0 },
     { 0, 0, 0, 0 }
 };

You can't do this - as element of your matrix is not of the same size.

 int[,] matrix_error = {
     { 0, 0, 0, 1 },
     { 0, 1 },
     { 0, 0, 1, 0 },
     { 1, 0 },
     { 0, 0, 0, 0 }
 };

To traverse it,


int[,] matrix = {
    { 1, 2, 3, 4 },
    { 5, 6, 7, 8 },
    { 9, 10, 11, 12 },
    { 1, 0, 0, 0 },
    { 0, 0, 0, 0 }
};

var m = matrix.GetLength(0);
var n = matrix.GetLength(1);

for (int row = 0; row < m; row++)
{
    for (int col = 0; col < n; col++)
    {
        Console.WriteLine(matrix[row, col]);
    }
}

Also notice how we accessing it using matrix[row, col]. 

Jagged int array

Jagged int array - int[][] - allow us to create a array of integer that has a variation of size. for example 

int[][] jaggedArray =
[
   [ 1,2 ],
   [ 2 ],
   [ 3,4]
];

To traverse through the jagged array 

for (int i = 0; i < jaggedArray.Length; i++)
{
    for (int j = 0; j < jaggedArray[i].Length; j++)
    {
        Console.WriteLine(jaggedArray[i][j]);
    }
}

Just some slight difference when it comes to accessing it - you will notice we are using jaggedArray.Length then follow by jaggedArray[i].Length. 



Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm