am a novice programmer and I was mingling with pointers to get my base strong for DSA . The following is my code
int main() {
int AnArray[20];
int* plocation6, * plocation0;
plocation6 = &AnArray[6];
plocation0 = &AnArray[0];
cout << (int)plocation6 << endl << (int)plocation0<<endl;
cout << "Difference " << plocation6 - plocation0;
}
And i expected that the value of Difference would be 24 as in Hexadecimal the pointer locations differ by 18 and by 24 in decimal but the answer comes out to be 6 where as if i use convert them using (int) and then do the operation then i get 24 as answer , Why is that? please expalin why 6 comes??
To build on top of the previous answers:
It is true, since an int
takes 4 bytes, that the two pointers are 24 bytes apart.
The reason that you are getting 6 is because the -
operator (for pointers) is defined as the difference between the two pointer's addresses divided by the size of the data type the pointers point to.
This is a similair concept to operator overloading, where an operator is defined to do something other than the typical operation.
Note: I dont think this is technically operator overloading, but understanding operator overloading will help to understand this concept.