Home >Backend Development >C++ >Give an example of pointer addition and subtraction in C
Pointers have many simple concepts that are very important for C programming.
The following explains two pointer arithmetic concepts, namely C pointer addition and subtraction.
C pointer addition refers to adding a value to a pointer variable.
The formula is as follows −
new_address= current_address + (number * size_of(data type))
The following is a C program for C pointer addition:
Demonstration
#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 </p><p>",ptr); ptr=ptr+7; //adding 7 to pointer variable printf("after adding add of ptr is %u </p><p>",ptr); return 0; }
When the above program is executed, it produces the following result −
add of ptr is 6422036 after adding add of ptr is 6422064
It subtracts a value from a pointer variable. Subtracting any number from a pointer variable results in an address.
The formula is as follows −
new_address= current_address - (number * size_of(data type))
The following is a C program for C pointer subtraction
Real-time demonstration
#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 </p><p>",ptr); ptr=ptr-5; //subtract 5 to pointer variable printf("after sub Addr of ptr is %u </p><p>",ptr); return 0; }
When the above program is executed, it produces the following results −
addr of ptr is 6422036 after sub Addr of ptr is 6422016
The above is the detailed content of Give an example of pointer addition and subtraction in C. For more information, please follow other related articles on the PHP Chinese website!