An array name is a constant pointer to the first element of the array. Therefore, in this declaration,
int balance[5];
balance is a pointer to &balance[0], which is the address of the first element of the array.
Example
In this code, we have a pointer ptr that points to the address of the first element of an integer array called balance.
#include <stdio.h>intmain(){int*ptr;int balance[5]={1,2,3,4,5};
ptr = balance;printf("Pointer 'ptr' points to the address: %d", ptr);printf("\nAddress of the first element: %d", balance);printf("\nAddress of the first element: %d",&balance[0]);return0;}
Output
In all the three cases, you get the same output −
Pointer 'ptr' points to the address: 647772240
Address of the first element: 647772240
Address of the first element: 647772240
If you fetch the value stored at the address that ptr points to, that is *ptr, then it will return 1.
Array Names as Constant Pointers
It is legal to use array names as constant pointers and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].
Once you store the address of the first element in “ptr“, you can access the array elements using *ptr, *(ptr + 1), *(ptr + 2), and so on.
Example
The following example demonstrates all the concepts discussed above −
#include <stdio.h>intmain(){/* an array with 5 elements */double balance[5]={1000.0,2.0,3.4,17.0,50.0};double*ptr;int i;
ptr = balance;/* output each array element's value */printf("Array values using pointer: \n");for(i =0; i <5; i++){printf("*(ptr + %d): %f\n", i,*(ptr + i));}printf("\nArray values using balance as address:\n");for(i =0; i <5; i++){printf("*(balance + %d): %f\n", i,*(balance + i));}return0;}
Output
When you run this code, it will produce the following output −
Array values using pointer:
*(ptr + 0): 1000.000000
*(ptr + 1): 2.000000
*(ptr + 2): 3.400000
*(ptr + 3): 17.000000
*(ptr + 4): 50.000000
Array values using balance as address:
*(balance + 0): 1000.000000
*(balance + 1): 2.000000
*(balance + 2): 3.400000
*(balance + 3): 17.000000
*(balance + 4): 50.000000
In the above example, ptr is a pointer that can store the address of a variable of double type. Once we have the address in ptr, *ptr will give us the value available at the address stored in ptr.
Leave a Reply