What I Know
I know that arrays int ary[]
can be expressed in the equivalent "pointer-to" format: int* ary
. However, what I would like to know is that if these two are the same, how physically are arrays stored?
I used to think that the elements are stored next to each other in the ram like so for the array ary
:
int size = 5;
int* ary = new int[size];
for (int i = 0; i < size; i++) { ary[i] = i; }
This (I believe) is stored in RAM like: ...[0][1][2][3][4]...
This means we can subsequently replace ary[i]
with *(ary + i)
by just increment the pointers' location by the index.
The Issue
The issue comes in when I am to define a 2D array in the same way:
int width = 2, height = 2;
Vector** array2D = new Vector*[height]
for (int i = 0; i < width; i++) {
array2D[i] = new Vector[height];
for (int j = 0; j < height; j++) { array2D[i][j] = (i, j); }
}
Given the class Vector
is for me to store both x, and y in a single fundamental unit: (x, y).
So how exactly would the above be stored?
It cannot logically be stored like
...[(0, 0)][(1, 0)][(0, 1)][(1, 1)]...
as this would mean that the(1, 0)
th element is the same as the(0, 1)
th.It cannot also be stored in a 2d array like below, as the physical RAM is a single 1d array of 8 bit numbers:
...[(0, 0)][(1, 0)]...
...[(0, 1)][(1, 1)]...
Neither can it be stored like
...[&(0, 0)][&(1, 0)][&(0, 1)][&(1, 1)]...
, given&(x, y)
is a pointer to the location of(x, y)
. This would just mean each memory location would just point to another one, and the value could not be stored anywhere.
Thank you in advanced.