Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two ways of declaring an array? [duplicate]

Tags:

c#

What is the difference between:

int [][] myArray;

and

int [,] myOtherArray;
like image 318
Rita Avatar asked Mar 22 '11 18:03

Rita


2 Answers

The first is a jagged array: an array where each item in the array is another array

int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];

The second is a multidimensional array, aka a matrix.

int[,] array = new int[4, 2]; // create a 4 by 2 matrix
like image 135
JoDG Avatar answered Sep 21 '22 21:09

JoDG


myArray is a jagged array, or an array of arrays. Each element of myArray is itself an int[].

myOtherArray is a rectangular (or multidimensional) array - a single object containing all the data directly.

Which you should use really depends on the situation. Sometimes it can be handy to have an array for each "row" of data (with the ability to replace whole rows, and have rows with different lengths), whereas at other times it makes sense to force a uniform layout.

like image 30
Jon Skeet Avatar answered Sep 21 '22 21:09

Jon Skeet