Pointer Arithmetic

We have already seen that if aptr is a pointer to a, then aptr + 1 increments apt tO pointto a [1], and aptr + i increments aptr to point to a (ij, and so on. Now consider the following code sequence

char aptr = "Something";

printf( "The string is %s", aptr);        /* prints ptr as it would any ordinary string */

Output:

The string is Something:

aptr++; /* increments aptr by one so that aptr now points to the second character in the string "Something" */

printf("The string is %s", aptr); /* again prints ptr ag it would any ordinary string */           

Output:

The string is something

Now consider another situation, that aptr is a pointer to int. Here incrementing aptr by one will not make it point to the next memory location but to the next element of the array. This is because whenever an integer variable is declared, tour bytes of memory are allocated to it (i.e.. the size of int is four, this size varies from system to system, in some systems it may be two). So when any such arithmetic is done on pointers the following calculation is performed

New address (of pointer) = old address + number incremented * size of datatype

Note

Size of datatype is I for char, 4 for int (machine dependent), 4 for float, 8 for double etc.

Pointer Arithmetic using Multi-Dimensional Arrays

Consider the following declaration

int int_ptr[3] [4] = {

{1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12}

}

  • The above statement declares an array of three pointers, pointing to arrays of four pointers each. Here, *int_ptr actually points to int_ptr[1], since in this case int ptr[0] means int_ptr[0][0]. *(*int_ptr)   retrieves the value 1
  • Since int_ptr is a pointer to a pointer, incrementing it by 1 makes it point to the next pointer in the array. Hence *(int_ptr + 1) makes it point to int_ptr[1]. And *(*int_ptr+1) is equal to 5.