Pointer Arithmetic in C Language
Categories: C language
We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be a pointer if the other operand is of type integer. In pointer-from-pointer subtraction, the result will be an integer value. Following arithmetic operations are possible on the pointer in C language:
1. Increment
2. Decrement
3. Addition
4. Subtraction
5. Comparison
Incrementing Pointer in C
If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This is somewhat different from the general arithmetic since the value of the pointer will get increased by the size of the data type to which the pointer is pointing.
We can traverse an array by using the increment operation on a pointer which will keep pointing to every element of the array, perform some operation on that, and update itself in a loop.
Traversing an array by using pointer
#include<stdio.h>
void main ()
{
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
int i;
printf("printing array elements...\n");
for(i = 0; i< 5; i++)
{
printf("%d ",*(p+i));
}
}
Output
printing array elements...
1 2 3 4 5