Pointers and Arrays in C programming

In this tutorial, we will learn how the pointers and arrays in C are related, difference between pointers and arrays.

Pointers and arrays are strongly related. Whenever an array name appears in an expression, it is automatically converted to a pointer to its first element.

Example:

pointer and arrays in C
fig: pointer and arrays in C

In above example,  will refer to the address  2886728 . As &a[0] references address so  &a[0] is equal to a. 

Arithmetic manipulation to Pointer


if p is a pointer to some element of an array, then p++ increments p to point to the next element

float num, array[10];
float *p1, *p2, *p3 = &array[5];
int i=2, j;
p1 = NULL; /* Assignment to NULL */
p2 = # /* Assignment to an address. */
p1 = p2; /* Assignment to another pointer (of same type). */
p2 = p3 - 4; /* Addition or subtraction by an integer */
p2 += i; /* Another pointer-offset expression. */
j = p3 - p2; /* Pointer subtraction: gives the number of elements between p2 and p3. */
i = p2 < p3; /* Relational operations <, >, ==, !=, <=, >= */

The arithmetic and relational operations are only valid for pointers to elements of the same array. 

Example:

//program to print sum of 2 numbers using pointer to an array
#include <stdio.h>
int main()
{
  int i, x[2], sum = 0;
  int *p;
  p = x;
  printf("Enter the number:");
  for( i = 0; i < 2; i++ )
  {
      scanf("%d",( p + i ));
      sum += *(p+i);
  }
  printf("Sum = %d", sum);
  return 0;
}

Output

Enter the numbers: 1
2
sum = 3

Difference between pointers and arrays in C programming


Lets define an array and a pointer.

char str[ ] = "liveoncode";
char *ptr = "liveoncode";

Lets see the difference

#include <stdio.h>

void main ()
{
   char str1[ ] = "liveoncode";
   char str2[ 50 ];

   char *ptr1 = "hello world";
   char *ptr2;

   //look carefully
   str2 = str1; //error
   ptr2 = ptr1; //valid

   str1 = "pointer"; //error because it is defined and initialized already

   ptr1 = "pointer"; //valid and works
}

Here, str1 and str2 are defined as array. And ptr1 and ptr2 as pointer.  It is clear that array of string cannot be assign to another string but pointer can be assigend to another pointer.