"yashwant pinge" <ya***********@gmail.comwrote in message
news:11**********************@d57g2000hsg.googlegr oups.com...
:
: int main()
: {
: int v1[10],v2[10];
: int i1 = &v1[5] - &v1[3];
: cout<<"i1:--"<<i1<<endl;
: return 0;
: }
:
: The above snipet gives the value of i is 2, why it is?
Because C (and C++) perform typed pointer arithmetic.
2 is indeed the number of integers stored between
the two addresses.
What value would you expect ?
: what is the return type of &v1[5] , &v1[3] and (v1[5] - &v1[3])?
In the above, the return type of &v1[i] is int*. The difference
of two pointers returns an integer of type std::diff_t.
If you want to compute the actual difference between byte
addresses, you should cast the pointers to (unsigned char*):
int i2 = ((unsigned char*)&v1[5] - (unsigned char*)&v1[3]);
( on most 32-bit platforms, the value of i2 will be 8 )
( casting to char/signed char works too, but unsigned char
should be used if you want to access the representation
of the stored data... )
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <
http://www.brainbench.com