![]() |
VOOZH | about |
A pointer to an array is a pointer that points to the whole array instead of the first element of the array. It considers the whole array as a single unit instead of it being a collection of given elements.
Example:
0x7ffde273ac20
In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays.
An array pointer can be declared as shown:
where,
For example,
Here ptr is pointer that points to an array of 10 integers. Since subscript have higher precedence than indirection, it is necessary to enclose the indirection operator and pointer name inside parentheses.
The following examples demonstrate the use pf pointer to an array in C and also highlights the difference between the pointer to an array and pointer to the first element of an array.
In the below code, the type of ptr is pointer to an array of 10 integers.
5 10 15
Normally, it is impossible to find the size of array inside a function, but if we pass the pointer to an array, the it is possible.
20
But again, we have to hardcode the size information.
The pointer that points to the 0th element of array and the array pointer that points to the whole array are totally different. The following program shows this:
p = 0x7fff81e4caf0 *ptr = 0x7fff81e4caf0 p = 0x7fff81e4caf4 *ptr = 0x7fff81e4cb04
Here, p is pointer to 0th element of the array arr, while ptr is a pointer that points to the whole array arr.
The following figure shows the pointer p and ptr. The darker arrow denotes a pointer to an array. (address may vary in each execution of the program)
On dereferencing a pointer expression, we get a value pointed to by that pointer expression. The pointer to an array point to an array, so on dereferencing it, we should get the array, and the name of the array denotes the base address. So, whenever a pointer to an array is dereferenced, we get the base address of the array to which it points.
The concept of pointer to an array can be extended to multidimensional arrays too:
1. Pointers to 2D Arrays
To define a pointer to a 2D array, both the number of rows and columns of the array must be specified in the pointer declaration.
Let's take a look at an example:
1 2 3 4 5 6
To define a pointer to a 2D array, both the number of rows and columns of the array must be specified in the pointer declaration.
Let's take a look at an example:
1 2 3 4 5 6 7 8 9 10 11 12