Pointer Arithmetic in C/C++

CC++Server Side Programming

Pointer arithmetic is used to implement arithmetic operations like addition subtraction, increment etc. in C language. There are four pointer arithmetic such as addition, subtraction, increment and decrement. In 32-bit machine, it increments or decrement the value by 2 and it will add or subtract 2* number. In 64-bit machine, it increments or decrement the value by 4 and it will add or subtract 4* number.

Here is an example of pointer arithmetic in C language,

Example

 Live Demo

#include<stdio.h>
int main() {
   int val = 28;
   int *pt;
   pt = &val;
   printf("Address of pointer : %u\n",pt);
   pt = pt + 5;
   printf("Addition to pointer : %u\n",pt);
   pt = pt - 5;
   printf("Subtraction from pointer : %u\n",pt);
   pt = pt + 1;
   printf("Increment to pointer : %u\n",pt);
   pt = pt - 1;
   printf("Decrement to pointer : %u\n",pt);
   return 0;
}

Output

Address of pointer : 3938439860
Addition to pointer : 3938439880
Subtraction from pointer : 3938439860
Increment to pointer : 3938439864
Decrement to pointer : 3938439860

In the above program, the arithmetic operations (addition, subtraction etc.) are applied to the pointer variable *pt.

int *pt;
pt = &val;
printf("Address of pointer : %u\n",pt);
pt = pt + 5;
printf("Addition to pointer : %u\n",pt);
pt = pt - 5;
printf("Subtraction from pointer : %u\n",pt);
pt = pt + 1;
printf("Increment to pointer : %u\n",pt);
pt = pt - 1;
printf("Decrement to pointer : %u\n",pt);
raja
Published on 05-Nov-2018 11:31:51
Advertisements