Programming in "C‟ | Describe addition and subtraction operations on pointer. Give suitable example for each.

In C, pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language: 

1. Increment/addition

2. Decrement/subtraction 

1. Increment: 

It is used to increment the pointer. Each time a pointer is incremented, it points to the next location with respect to memory size. 

Example, 

If ptr is an integer pointer stored at address 1000, then ptr++ shows 1002 as incremented location for an int. It increments by two locations as it requires two bytes storage. 

OR

1. Addition 

When addition operation is performed on pointer, it gives the location incremented by the added value according to data type.

Example:

If ptr is an integer pointer stored at address 1000, Then ptr+2 shows 1000+(2*2) = 1004 as incremented location for an int.

2. Decrement:

It is used to decrement the pointer. Each time a pointer is decremented, it points to the previous location with respect to memory size. 

Example, 
If the current position of pointer is 1002, then decrement operation ptr-- results in the pointer pointing to the location 1000 in case of integer pointer as it require two bytes storage. 

OR

2. Subtraction

When subtraction operation is performed on the pointer variable, it gives the location decremented by the subtracted value according to data type.

Example:

If ptr is an integer pointer stored at address 1004,
Then ptr-2 shows 1004-(2*2) = 1000 as decremented location for an int. 

Post a Comment

0 Comments