Interviews1 answer
what is difference between int[,] arr=new int[4,2] && int[][] arr=new int[4][2];
1 Answer
Use an int[,] when you want to ensure that the rows are all the same. Another use of int[,] is for interoperability purposes to C++ pseudo-multidimensional arrays. Another benefit is that the entire memory block is allocated at once.
Use and int[][] when you want to allow a more complex data structure, that allows the rows to be different lengths. The rows could even be null. But you will have to loop over a for loop:
int [][] x = new int[10][];
for (int i = 0; i < 10; i++) x[i] = new int[10];
Another benefit to int[][] is that the memory here does not need to be allocated contiguously. Even if you use an int[][] of all the same dimensions, this can be a benefit. It is the difference of finding space for 10 lengths of 10 elements, to finding the space for 1 length of 100 elements. (Or a real wold analogy, finding space in you bag for 10 pairs of socks vs 1 pair of pants. The volume is about the same, but you can jam those sock just about anywhere). That's good if you have smaller amounts of space available.
Satish RajnalePosted Feb 28, 2014, 7:16 PM EST

