Pointers and Arrays
Arrays and pointers are very closely linked together. In most contexts, C++ treats the name of an array as if it were a pointer i.e. memory address of some element. C++ interprets an array name as the address of its first element. That is, if age is an int array to hold 10 integers then age stores the address of age[0], the first element of the array. Consider the following code snippet:
In the above code, a is a pointer to integer and age is an array holding 10 integers. The pointer a is made to point to where age is pointing to. When the data values of these pointers are printed, both values come out to be the same. Thus from the above given code, it is proved that the name of an array is actually a pointer that points to the first element of the array.
Since the name of the array is a pointer to its first element, the arrayname + 1 gives the address of the second element of the array, arrayname + 2 gives the address of the third element and so forth.
Array of pointers
Pointers may also be arrayed like any other data type. To declare an array holding 10 int pointers, the declaration would be as follows:
After this declaration, contiguous memory would be allocated for 10 pointers that can point to integers.
Now each of the pointers or the elements of pointer array can be initialized. To assign the address of an integer variable amount to the forth element of the pointer array, we will write
Comments - No Responses to “Pointers and Arrays”
Sorry but comments are closed at this time.