Newbie question: Arrays

  • Thread starter Thread starter Blue Streak
  • Start date Start date
B

Blue Streak

What exactly is the difference (besides syntax) when you declare multi-
dimentional arrays this way?

int [] [] a = new int[3][3];

int [,] b = new int[3,3];

// What's the difference between a and b?

TIA...
 
Blue Streak said:
What exactly is the difference (besides syntax) when you declare multi-
dimentional arrays this way?

int [] [] a = new int[3][3];

int [,] b = new int[3,3];

// What's the difference between a and b?

a is a single dimension array of single dimension arrays of ints.

b is a dual dimension array of ints.
 
Blue Streak,
int [] [] a = new int[3][3];

Once initialized you will have four arrays. That consumes more
memory, and a[1][2] requires two array lookups.
int [,] b = new int[3,3];

Creates one multidimensional array (a feature of the CLR). Consumes
less memory and a[1,2] requires one lookup.

Oddly enough int[][] is ~10% faster even with the extra lookup. This
is because the Microsoft has optimized the shit out of single
dimension, 0 indexed arrays. If you are planning to iterate over your
arrays I would use int[][], but if you need many dimensions with
infrequent access int[,] will save on memory.

-James
 
Blue said:
What exactly is the difference (besides syntax) when you declare multi-
dimentional arrays this way?

int [] [] a = new int[3][3];

int [,] b = new int[3,3];

// What's the difference between a and b?

To expand on what Anthony wrote...

In the former case, the primary index returns individual arrays, and so
allows for "jagged" arrays. That is, each sub-array can be of different
size (if you allocate it that way...your example doesn't).

In the latter case, you have a traditional multi-dimensional array,
where each row of the array has the same number of columns.

In both cases, you aren't actually limited to 2 dimensions, so the
behaviors extend as you add dimensions.

Pete
 
Blue said:
What exactly is the difference (besides syntax) when you declare multi-
dimentional arrays this way?

int [] [] a = new int[3][3];

int [,] b = new int[3,3];

// What's the difference between a and b?

TIA...

The main difference is that a is an array of arrays (a jagged array),
while b is a two dimensional array.

Another difference is the the code for b works, but the code for a doesn't.

To create an array of arrays, you have to create the arrays in the array
separately:

int[][] a = new int[3][];
a[0] = new int[3];
a[1] = new int[3];
a[2] = new int[3];
 
Back
Top