C Programming Tutorial
About Lesson

C Pointers & Arrays

In this tutorial, we will learn about the relation between pointers and array, accessing elements of array using pointers in C programming with the help of examples.

To learn about Pointers and Arrays click on the given links.


Relation between Pointers and Arrays

 

Example : Program to make array of pointers

#include <stdio.h>
int main() {
  int pointer_array[5], a;
  for(a = 0; a < 4; ++a) {
  //We have %p format specifier for pointers
  printf("&pointer_array[%d] = %p\n", a, &pointer_array[a]);
  }
  printf("Address of array = %p", pointer_array);
  //array of address is same as array first elements address
  return 0;
}

Output

&pointer_array[0] = 0x7ffd8eb6b740
&pointer_array[1] = 0x7ffd8eb6b744
&pointer_array[2] = 0x7ffd8eb6b748
&pointer_array[3] = 0x7ffd8eb6b74c
Address of array = 0x7ffd8eb6b740

 

There are always the same bytes of difference between the addresses of two consecutive elements as the size of the datatype of an array.

In the above example, the difference between the two consecutive elements is 4 bytes because the size of int datatype is 4 bytes.

Note : The address of &pointer_array[0] and pointer_array is the same because the variable pointer_array points to the first element of the array.

In the above example, &pointer_array[0] is equivalent to pointer_array and pointer_array[0] is equivalent to *pointer_array.


Working of C Pointers with Arrays
Working of C Pointers with Arrays

Similarly,

  • &pointer_array[1] is equivalent to pointer_array+1 and pointer_array[1] is same as *(pointer_array+1).
  • &pointer_array[2] is equivalent to pointer_array+2 and pointer_array[2] is same as *(pointer_array+2).
  • Basically, &pointer_array[i] is equivalent to pointer_array+i and pointer_array[i] is same as *(pointer_array+i).

Example : printing Array elements using Pointer

#include <stdio.h>
int main() {
  int i, pointer_array[5], sum = 0;
  printf("Enter Five numbers: ");
  for(i = 0; i < 6; ++i) {
    scanf("%d", pointer_array+i);
    // Equivalent to scanf("%d", &pointer_array[i]);
    sum += *(pointer_array+i);
    // Equivalent to sum += pointer_array[i]
  }
  printf("Sum = %d", sum);
  return 0;
}

Output :

Enter Five numbers: 1
4
6
3
2
Sum = 16

 

error: Content is protected !!