Loading....
Coupon Accepted Successfully!

 

Arithmetic Operations With Pointers

We can perform different arithmetic operations by using pointers. Increment, decrement, prefix, and postfix operations can be performed with pointers. The effects of these operations are shown in Table.
 
Table: Pointers and Arithmetic Operations
 

Data Type

Initial Address

Operation

Address After Operations

Required Bytes

int i = 2

4046

++

--

4048

4044

2

char c = ‘x’

4053

++

--

4054

4052

1

float f =2.2

4058

++

--

4062

4054

4

long l = 2

4060

++

--

4064

4056

4


From the above table, while referring to the first entry, we can observe that on increment of the pointer variable for integers, the address is incremented by two; that is, 4046 is the original address and on increment, its value will be 4048, because integers require two bytes. Similarly, when the pointer variable for integer is decreased, its address 4048 becomes 4046.


Similarly, for characters, floating point numbers and long integers require 1, 4, and 4 bytes, ­respectively. After the effect of increment and decrement, the memory locations are shown in Table.

The following program explains the increase and decrease of pointers:
 

13.4 Program on pointer incrementation and decrementation.

#include<iostream.h>

#include<conio.h>

int main()

{

clrscr();

int x=10;

int *p;

p=&x;

cout<<“\n Address of p:”<<unsigned(p);

p=p+4;

cout<<“\n Address of p:”<<unsigned(p);

p=p-2;

cout<<“\n Address of p:”<<unsigned(p);

return 0;

}

OUTPUT

Address of p:65524

Address of p:65532

Address of p:65528

 

Explanation: In the above program, p holds the address of x. The initial address of x is 65524. When p is incremented by 4, it means that the address is increased by 8, because each integer needs two bytes. Here, the address obtained is 65532. Similarly, when the address of x is decreased to 2, the address finally obtained is 65528.

 

13.5 Program on changing the values of variables using pointer.

#include<iostream.h>

#include<conio.h>

int main()

{

clrscr();

int x=10;

int *p;

p=&x;

cout<<“\n Value of x:”<<*p;

*p=*p+10;

cout<<“\n Value of x:”<<*p;

*p=*p-2;

cout<<“\n Value of x:”<<*p;

return 0;

}

OUTPUT

Value of x:10

Value of x:20

Value of x:18

 

Explanation: In the above program using pointers, the value of the variable x is first increased and then decreased.




Test Your Skills Now!
Take a Quiz now
Reviewer Name