C Tutorial C References

C - Pointers and Arrays



The concept of arrays is strongly related to pointers. A pointer that points to the beginning of an array can access the array by using either pointer arithmetic or array-style indexing. Pointers and arrays support the same set of operations, with the same meaning for both. The main difference being that pointers can be assigned new addresses, while arrays will always represent the same address blocks.

Example: pointer to an array

In the example below, an array called Arr and a pointer called p are created. Then the pointer p is assigned to Arr which makes it pointing to the beginning of the array i.e, Arr[0]. After that the pointer arithmetic and array-style indexing are used to assign values to all elements of the Arr.

#include <stdio.h>
 
int main (){
  int Arr[5];
  int *p;

  p = Arr;       //pointing to Arr[0]
  *p = 100;   
  p++;           //pointing to Arr[1]
  *p=200; 
  p = &Arr[2];   //pointing to Arr[2]
  *p = 300; 
  p = Arr + 3;   //pointing to Arr[3]
  *p = 400; 
  p = Arr;       //pointing to Arr[0]
  *(p+4) = 500;  //assigning Arr[4]

  for (int i = 0; i <= 4; i++){
    printf("%i\n",Arr[i]); 
  }
  return 0;
}

The output of the above code will be:

100
200
300
400
500

Example: access array elements using pointers

Consider one more example, where elements of an array are accessed using pointers.

#include <stdio.h>
 
int main (){
  int Arr[3] = {10, 20, 30};
  int *p;

  p = Arr;       //pointing to Arr[0]

  for (int i = 0; i < 3; i++){
    printf("(p + %i) = %p\n", i, (p+i)); 
    printf("*(p + %i) = %i\n", i, *(p+i)); 
  }
  return 0;
}

The output of the above code will be:

(p + 0) = 0x7fffa02bb04c
*(p + 0) = 10
(p + 1) = 0x7fffa02bb050
*(p + 1) = 20
(p + 2) = 0x7fffa02bb054
*(p + 2) = 30

❮ C - Pointers