Saturday, 14 September 2013

How to calculate address subtraction in c++

How to calculate address subtraction in c++

I am a little surprised by the output of the following code:
double array[] = {4, 5, 6, 8, 10, 20};
double* p = array + 3;
//Print array address
cout << (unsigned long)(array) << endl; //This prints 1768104
cout << (unsigned long)(p) << endl; //This prints 1768128
//print p - array
cout << (unsigned long)(p - array) << endl; // This prints 3
I am surprised that the last line prints 3. Shouldn't it print 24 = 3 * 8
bytes? Also, as expected, the address of p is the address of array + 3 * 8
bytes. This seems inconsistent. In fact, it is not even a legal assignment
to write: p = p - array; // can't assign an int to type double* No idea,
why this is an int.

No comments:

Post a Comment