The basic idea of Pointer to an Array is that a pointer is used in with array that points to the address of the first element of that array.
Before we begin, you need to have the knowledge of following C programming:
Consider the following:
1 2 3 4 | double *ptr; double arr[10]; ptr = arr; |
In the above example, the variable arr will provide the base address, which is a constant pointer pointing to the first element of the array that is to arr[0]. And hence the arr will contain the address of arr[0]. Thus, the above program fragment assigns ptr with the address of the arr.
Once the address of the first element is stored in the pointer ‘p’, we can access other elements of array elements using *p, *(p+1), *(p+2)
, and so on.
Now lets apply it in a programs.
Example 1: Array and Pointers in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <stdio.h> int main() { int i; int arr[5] = { 30, 42, 35, 4, 52 }; int *p = arr; //displaying using pointer for (i = 0; i < 5; i++) { printf("Element at %d = %d\n", i, *p); p++; } return 0; } |
Output:
1 2 3 4 5 | Element at 0 = 30 Element at 1 = 42 Element at 2 = 35 Element at 3 = 4 Element at 4 = 52 |
Example 2: Array and Pointers in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <stdio.h> int main() { int arr[6] = {10, 20, 30, 40, 50, 60}; int *ptr; //4th element address is assigned ptr = &arr[3]; printf("Value pointed by *ptr: %d \n", *ptr); // 40 printf("Value pointed by *(ptr+1): %d \n", *(ptr+1)); // 50 printf("Value pointed by: *(ptr-1): %d", *(ptr-1)); // 30 return 0; } |
Output:
1 2 3 | Value pointed by *ptr: 40 Value pointed by *(ptr+1): 50 Value pointed by: *(ptr-1): 30 |
In the above example array(arr) 4th element’s address is assigned to the pointer(ptr) and through that, we can print the value that the pointer points to by simply incrementing decrementing the pointer value such as by using ptr+1 or ptr-2, etc.