Pointer arithmetic

I have a confusion here.....

"... the behaviour is undefined for arithmetic or comparisons with pointers that do not point to members of the same array. (There is one exception: the address of the first element past the end of an array can be used in pointer arithmetic" - K & R.

But I am still not getting if this kind of arithmetic is defined by standard or not?

short *i = (short *)60;
short *j = (short *)20;
printf("%d\n", i - j);

Though, gcc always gives answer based on (i - j)/sizeof(short), but this could be gcc implementation specific. Can someone tell me if this is defined by C standard or not?

TIA
I think the standard is clear - your code is wrong. But I'm sure it will work in 99.99% of cases.

Why do you need to use this kind of technique? The only use I can think of is to access hardware registers or similar lowest-level programming. Are you implementing a driver or something like that?

EDIT: Actually, in my opinion even the line "short *i = (short *)60;" is wrong because you're assuming that pointer is simply a number containing an address, and there is no such assumption in the standard.
Last edited on
Topic archived. No new replies allowed.