Pointer Arithmetic
In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:Incrementing Pointer
Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location. Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given:
new_address= current_address + i * size_of(data type)
#include <stdio.h> void main(){ int number = 40; int *p; //pointer to int p=&number; //stores the address of number variable printf("Address of p variable is %u \n",p); p=p+1; printf("After increment: Address of p variable is %u \n",p); } Output Address of p variable is 32104 After increment: Address of p variable is 32112
Decrementing Pointer
new_address= current_address - i * size_of(data type)
#include <stdio.h> void main(){ int number=50; int *p; //pointer to int p = &number; //stores the address of number variable printf("Address of p variable is %u \n",p); p = p-1; printf("After decrement: Address of p variable is %u \n",p); } Output Address of p variable is 321100 After decrement: Address of p variable is 32192
Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is given:
new_address= current_address + (number * size_of(data type))
#include <stdio.h> #includevoid main() { int number = 40; int *p; //pointer to int p=&number;//stores the address of number variable printf("Address of p variable is %u \n",p); p=p+2; //adding 2 to pointer variable printf("After adding 2: Address of p variable is %u \n",p); } Output: Address of p variable is 321100 After adding 2: Address of p variable is 321116
Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given :
new_address= current_address - (number * size_of(data type))
#include <stdio.h> #includevoid main() { int number = 50; int *p; //pointer to int p=&number; //stores the address of number variable printf("Address of p variable is %u \n",p); p=p-2; //subtracting 2 from pointer variable printf("After subtracting 2: Address of p variable is %u \n",p); } Output: Address of p variable is 321100 After subtracting 2: Address of p variable is 321084