Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D array vs array of arrays

What is the difference between a 2D array and an array of arrays?

I have read comments, such as @Dave's, that seem to differentiate between the two.

This breaks if he's using 2d arrays, or pointer-to-array types, rather than an array of arrays. – Dave

I always thought that both referred to:

int arr_arr[][];

EDIT: @FutureReader, you may wish to see How do I use arrays in C++?

like image 423
Mateen Ulhaq Avatar asked Oct 31 '11 02:10

Mateen Ulhaq


People also ask

What is the difference between a 2D array and an array of arrays?

A one-dimensional array stores a single list of various elements having a similar data type. A two-dimensional array stores an array of various arrays, or a list of various lists, or an array of various one-dimensional arrays. It represents multiple data items in the form of a list.

Is a 2D array just an array of arrays?

A 2D array is a 1D array of (references to) 1D arrays. int[][] rating = new int[3][4];

Is 2D array and multidimensional array same?

Two – dimensional array is the simplest form of a multidimensional array.

What is array and 2D array?

A one-dimensional array can be seen as data elements organised in a row. A two-dimensional array is similar to a one-dimensional array, but it can be visualised as a grid (or table) with rows and columns. For example, a nine-by-nine grid could be referenced with numbers for each row and letters for each column.


2 Answers

There are four different concepts here.

  • The two-dimensional array: int arr[][]. It cannot be resized in any direction, and is contiguous. Indexing it is the same as ((int*)arr)[y*w + x]. Must be allocated statically.
  • The pointer-to array: int (*arr)[]. It can be resized only to add more rows, and is contiguous. Indexing it is the same as ((int*)arr)[y*w + x]. Must be allocated dynamically, but can be freed free(x);
  • The pointer-to-pointer: int **arr. It can be resized in any direction, and isn't necessarily square. Usually allocated dynamically, not necessarily contiguous, and freeing is dependent on its construction. Indexing is the same as *(*(arr+y)+x).
  • The array-of-pointers: int *arr[]. It can be resized only to add more columns, and isn't necessarily square. Resizing and freeing also depends on construction. Indexing is the same as *(*(arr+y)+x).

Every one of these can be used arr[y][x], leading to the confusion.

like image 196
Dave Avatar answered Oct 03 '22 03:10

Dave


A 2 dimensional array is by definition an array of arrays.

What Dave was saying is that in that context, there are different semantics between the definition of a 2D array like this:

int x[][];

this:

int *x[];

or this:

int **x;
like image 40
Jacob Relkin Avatar answered Oct 03 '22 03:10

Jacob Relkin