首页 > 文章列表 > 给出一个C指针加法和减法的例子

给出一个C指针加法和减法的例子

指针加法 C指针运算 指针减法
326 2023-08-20

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

输出

当上述程序被执行时,它产生以下结果 −

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

C指针减法

它从指针变量中减去一个值。从指针变量中减去任何数字都会得到一个地址。

公式如下 −

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

输出

当上述程序被执行时,它产生以下结果 −

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