# Operators : Pointer Arithmetic

0 like 0 dislike
4 views

0 like 0 dislike
by Goeduhub's Expert (7.8k points)

Given a pointer and a scalar type N, evaluates into a pointer to the Nth element of the pointed-to type that directly succeeds the pointed-to object in memory.

int arr[] = {1, 2, 3, 4, 5};

printf("*(arr + 3) = %i\n", *(arr + 3)); /* Outputs "4", arr's fourth element. */

It does not matter if the pointer is used as the operand value or the scalar value. This means that things such as 3 + arr are valid. If arr[k] is the k+1 member of an array, then arr+k is a pointer to arr[k]. In other words, arr or arr+0 is a pointer to arr, arr+1 is a pointer to arr, and so on. In general, *(arr+k) is same as arr[k].

Unlike the usual arithmetic, addition of 1 to a pointer to an int will add 4 bytes to the current address value. As array names are constant pointers, + is the only operator we can use to access the members of an array via pointer notation using the array name. However, by deﬁning a pointer to an array, we can get more ﬂexibility to process the data in an array. For example, we can print the members of an array as follows:

#include<stdio.h>

static const size_t N = 5

int main()

{

size_t k = 0;

int arr[] = {1, 2, 3, 4, 5};

for(k = 0; k < N; k++)

{

printf("\n\t%d", *(arr + k));

}

return 0;

}

By deﬁning a pointer to the array, the above program is equivalent to the following:

#include<stdio.h>

static const size_t N = 5

int main()

{

size_t k = 0;

int arr[] = {1, 2, 3, 4, 5};

int *ptr = arr; /* or int *ptr = &arr; */

for(k = 0; k < N; k++)

{

printf("\n\t%d", ptr[k]);

/* or   printf("\n\t%d", *(ptr + k)); */

/* or   printf("\n\t%d", *ptr++); */

}

return 0;

}

See that the members of the array arr are accessed using the operators + and ++. The other operators that can be used with the pointer ptr are - and --.

Pointer subtraction

Given two pointers to the same type, evaluates into an object of type ptrdiff_t that holds the scalar value that must be added to the second pointer in order to obtain the value of the ﬁrst pointer.

int arr[] = {1, 2, 3, 4, 5};

int *p = &arr;

int *q = &arr;

ptrdiff_t diff = q - p;

printf("q - p = %ti\n", diff); /* Outputs "1". */

printf("*(p + (q - p)) = %d\n", *(p + diff)); /* Outputs "4". */