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
Release: 2023-08-31 09:21:07
forward
1367 people have browsed it

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))
Copy after login

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;
}
Copy after login

Output

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

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

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))
Copy after login

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;
}
Copy after login

Output

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

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template