Re: pointer addition and structs

From: Steve Friedl [MVP/Security] (steve_at_unixwiz.net)
Date: 12/16/04


Date: Wed, 15 Dec 2004 18:27:21 -0800


"Mark Randall" <strike@rapiercom.freeserve.co.uk> wrote in message
news:u4GjN2w4EHA.1296@TK2MSFTNGP10.phx.gbl...
> foo f;
> long* p = &f + 16;

No, not at all, because pointer math is scaled by the size of the pointed-to
object: you're calculating an address that is far beyond the bounds of the
base structure "f". In raw terms, you are calculating:

long *p = &f + (16 * sizeof f);

which is required to support array notation. In C, saying

ary[5]

is precisely the same as

*(ary + 5)

Really: it's positively identical, so this scale-by-size has to be there or
this property would not work.

Curiously, this can be extrapolated such that these are all identical:

ary[5]
*(ary + 5)
*(5 + ary)
5[ary]

The latter is perfectly valid and well-formed C, though it's probably not
recommended.

Steve
---
Steve Friedl -- Tustin, California USA -- www.unixwiz.net
Unix Wizard -- Microsoft MVP/Security -- I speak for me only