Given this code:
int *p, *q;
p = (int *) 1000;
q = (int *) 2000;
What is q - p and how?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s actually undefined, according to the standard. Pointer arithmetic is not guaranteed to work unless the pointers are both pointing to either an element in, or just beyond, the same array.
The relevant section of the standard is 6.5.6:9 (n1362 draft of c1x but this hasn’t changed since c99) which states:
You’ll most likely get 250 if your
intdatatype is 4 bytes but there’s no guarantee. Undefined behaviour (unlike implementation-defined behaviour) means just that, undefined. Anything can happen, up to an including the total destruction of a large proportion of space-time.A refresher course: