Pointer arithmetic means adding or subtracting values to the pointer variable. This is not the same as those simple arithmetic operations in normal variables. So how pointer arithmetic is different from simple arithmetic is explained below.
Adding integer to pointer
Suppose ‘p’ is a pointer to the ‘a’ variable. If we are adding n to pointer ‘p’. Then the result will be the addition of the value of pointer and n times size of the data type of variable ‘a’.
So, Result of pointer arithmetic addition addition = pointer value + (size of data type of ‘a’) *(n)
Let’s understand it by an example
int a; int *p = &a; // suppose address of ‘a’ is 4024 p = p + 3;
Now for the resultant value of p, the pointer value is 4024, size of data type of ‘a’ is 2 bytes, value of n is 3. So value of
p = 4024(pointer value) + 2(size of data type of ‘a’) * 3(n)
= 4024 + 6
= 4030
Subtracting integer from pointer
Suppose ‘p’ is a pointer to the ‘a’ variable. If we are subtracting n to the pointer ‘p’. Then the result will be the subtraction of the value of pointer and n times size of the data type of variable ‘a’.
So, Result of pointer arithmetic addition addition = pointer value – (size of data type of ‘a’) *(n)
Let’s understand it by an example
int a; int *p = &a; // suppose address of ‘a’ is 4024 p = p - 3;
Now for the resultant value of p, the pointer value is 4024, size of data type of ‘a’ is 2 bytes, value of n is 3. So value of
p = 4024(pointer value) – 2(size of data type of ‘a’) * 3(n)
= 4024 – 6
= 4018
Example program to understand pointer arithmetic
In the below example, we are going to understand the addition of an integer to a pointer. Same thing you can understand for subtraction. In the below example address of a is 6487572. So the value of p is 6487572. And the results of p, p+1, p+2, p+3 are printed. By using this statement Result of pointer arithmetic addition = pointer value + (size of the data type of ‘a’) *(n).
p = 6487572 + 2 *0 = 6487572
p + 1 = 6487572 + 2*1 = 6487574
p + 2 = 6487572 + 2*2 = 6487576
p + 3 = 6487572 + 2*3 = 6487578
#include<stdio.h> #include<conio.h> void main() { int a=2; int *p = &a; clrscr(); printf("p = %u \n",p); printf("p + 1 = %u \n",p+1); printf("p + 2 = %u \n",p+2); printf("p + 3 = %u \n",p+3); getch(); }
Output:
Learning from this blog:
- What is pointer arithmetic that is different from simple arithmetic?
- What is the result of pointer arithmetic addition?
- What is the result of pointer arithmetic subtraction?
- General statement of pointer arithmetic result?
- How to write code for pointer arithmetic?