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++?
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.
A 2D array is a 1D array of (references to) 1D arrays. int[][] rating = new int[3][4];
Two – dimensional array is the simplest form of a multidimensional 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.
There are four different concepts here.
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.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)
;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)
. 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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With