Given an example of C pointer addition and subtraction



Pointers have many but easy concepts and they are very important to C programming.

Two of the arithmetic pointer concepts are explained below, which are C pointer addition and subtraction respectively.

C pointer addition

C pointer addition refers to adding a value to the pointer variable.

The formula is as follows −

new_address= current_address + (number * size_of(data type))

Example

Following is the C program for C pointer addition −

 Live Demo

#include<stdio.h>
int main(){
   int num=500;
   int *ptr;//pointer to int
   ptr=#//stores the address of number variable
   printf("add of ptr is %u 
",ptr);    ptr=ptr+7; //adding 7 to pointer variable    printf("after adding add of ptr is %u
",ptr);    return 0; }

Output

When the above program is executed, it produces the following result −

add of ptr is 6422036
after adding add of ptr is 6422064

C pointer subtraction

It subtracts a value from the pointer variable. Subtracting any number from a pointer variable will give an address.

The formula is as follows −

new_address= current_address - (number * size_of(data type))

Example

Following is the C program for C pointer subtraction −

 Live Demo

#include<stdio.h>
int main(){
   int num=500;
   int *ptr;//pointer to int
   ptr=#//stores the address of number variable
   printf("addr of ptr is %u 
",ptr);    ptr=ptr-5; //subtract 5 to pointer variable    printf("after sub Addr of ptr is %u
",ptr);    return 0; }

Output

When the above program is executed, it produces the following result −

addr of ptr is 6422036
after sub Addr of ptr is 6422016

Advertisements