875 views
0 votes
0 votes
we can subtract 2 pointer address then why we can't perform operations like addition, multiplication or division on pointer address???

any specific reason?

2 Answers

0 votes
0 votes

Why Subtraction is allowed? Two addresses can be subtracted because the memory between the two addresses will be valid memory. For example - Pointer ptr_1 is pointing to 0x1cb0010 memory location and ptr_2 is pointing to 0x1cb0030 memory location. If we subract ptr_1 from ptr_2, then the Memory region will lie in between these two location which is obviously a valid memory location.

 

Why addition, Multiplication or division is not allowed??
If we perform addition, multiplication or division on ptr_1 and ptr_2, then the resultant address may or may not be a valid address. That can be out of range or invalid address. This is the reason compiler doesn’t allow these operations on valid addresses.

0 votes
0 votes

Pointers are variables used to hold the address of other variables.

What is the result of subtraction of two pointers?

When two pointers of same type are subtracted then it returns number of elements between them. Similarly we can add or subtract integers to make a pointer to point to next or previous elements of the currently pointed elements. Mostly these operations are performed in context of arrays.

For  example, consider this example

int a [ ] = { 1, 2 ,3 , 4, 5 };
int *p=&a[0];
then a[i]= *(p+i)

 

Similarly if

int *q= &a[4];

then q-p will return number of elements between a[0] and a[4] which is 4.

There are no meaning to expressions such as p+q, p*q, p/q

 

 

edited by

Related questions

1 votes
1 votes
2 answers
4