Pointers & Multidimensional Arrays
Posted: March 25, 2014 Filed under: C/C++ | Tags: array, C, pointers Leave a commentI were troubled by the use of pointers to access array in C. I worked on it and created a method to deal with it.
- array_name is a constant pointer.
It points the first location of the array.
array_name = &array_name[0] *array_name = array_name[0]
Pointers are incremented by its sizeof(type).
array + i = &array_name[0] *array + i = array_name[i]
- 2D Array is an array of constant pointers.
So to access an element
array_name[i][j]
First you have to access constant pointer stored in the i-th location of the array pointed by pointer array_name. So increment array_name by i.
*(array_name+i)
Then you have to access the j-th location of the array pointed by the above pointer.
*(array_name+i)+j
To get the value of that location use the derefence operator.
*(*(array_name+i)+j)
- 3D Array is a 2D array of constant pointers
So to access an element
array_name[i][j][k]
First you have to access the pointer stored in the i-th location of the array pointed by the pointer array_name.
*(array_name)+i
Then you have to access the j-th element in that array
*(*(array_name)+i)+j
Which itself is a pointer. Increment it k times to get the k-th location.
(*(*(array_name)+i)+j)+k
Then derefernce it to get the value of that location.
*(*(*(array_name)+i)+j)+k)