Pointer is a special type of variable that holds memory address of another variable.
When you declare array like int arr[2] name of that array is actually becomes a pointer that holds address of the first data member of that array. Therefore, if you write:
int arr[2];
int *p;
p = arr;
you will assign value of pointer arr to pointer p and in this way p becomes alternative name for array arr. After such assignment you could use p to access array data members, like:
p[1] = 2;
will assign value 2 to the second element of the array arr, which is equivalent for
arr[1] = 2;
And if you wish to assign pointer not to the first but to second element in the array you could write:
p = &arr[1]; //assigns address of second array data member to the pointer
*p = 2; // assigns value to that member
This will be another equivalent for arr[1] = 2; operation.
When multidimensional (2d, 3d …) array is declared, you should understand that it will be stored in memory as 1d array no matter how many formal dimensions it has. If you declare array x[2][3] it will be stored in memory as a single sequence: x[0][0], x[0][1], x[0][2], x[1][0], x[1][1], x[1][2], x[2][0], x[2][1], x[2][2].
Therefore you could use pointers to access data in 2d array the same way as if it was 1d array.
Let’s say we have 2d array that holds 8 members (4 rows by 2 columns):
int bb[4][2];
int *p;
p = (int*)bb; //will assign pointer bb value to p (with type conversion)
Now data members of array bb could be accessed using pointer p as if it points to 1d array:
p[0] is equivalent of bb[0][0]
p[1] is equivalent of bb [0][1]
p[2] is equivalent of bb [1][0]
p[3] is equivalent of bb [1][1]
p[4] is equivalent of bb [2][0]
p[5] is equivalent of bb [2][1]
p[6] is equivalent of bb [3][0]
p[7] is equivalent of bb [3][1]
Type conversion (int *) is needed because here array name (which is a pointer) bb points not to the first single integer array member, but to array that consists of single “row” of two integers, therefore bb is a pointer to pointer to first data member of 2 integers sequence. But if you declare p as pointer to pointer, you could access array data members without type conversion during assignment:
int bb[4][2];
int **p; //pointer to pointer
p = bb;
p[2][1] = 10; // equivalent to bb[2][1] = 10;
Comments
Leave a comment