Home >Backend Development >C++ >Give an example of pointer addition and subtraction in C

Give an example of pointer addition and subtraction in C

WBOY
WBOYforward
2023-08-31 09:21:071333browse

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

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))

Example

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;
}

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 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))

Example

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;
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more