Pointers and arrays in C language

In C, arrays are effectively just pointers to the array’s initial element. As a result, we may utilize pointer arithmetic to access the other array elements.

Example:

#include <stdio.h>

int main() {
   int arr[] = {10, 20, 30, 40, 50};
   int *p = arr;

   printf("The value at arr[0] is %d\n", arr[0]);
   printf("The value at *p is %d\n", *p);

   printf("The value at arr[2] is %d\n", arr[2]);
   printf("The value at *(p+2) is %d\n", *(p+2));

   printf("The address of arr[0] is %p\n", &arr[0]);
   printf("The address of p is %p\n", p);

   return 0;
}

Output:

The value at arr[0] is 10
The value at *p is 10
The value at arr[2] is 30
The value at *(p+2) is 30
The address of arr[0] is 0x7fff5a688d30
The address of p is 0x7fff5a688d30

In the example above, we declare the array arr and give it some initial values. The next step is to declare a pointer, p, and initialize it with the address of the array’s first element, arr.

To gain access to the other items in the array, we use pointer arithmetic. For instance, *(p+2) provides us with the array element’s third value.

Since that arrays are simply pointers to the array’s first element, we also compare the addresses of arr[0] and p, which are identical.