Neatest way to get the end pointer?




I commonly use pointers to iterate thru an array. For example:

int my_array[X];

int *p = my_array;
int const *const pend = my_array + sizeof my_array/sizeof*my_array;

do *p++ = 42;
while (pend != p);

(Yes I realise the lack of spaces in the sizeof thing above is
disgusting, but I've gotten so sick of writing it out that I make it as
compact as possible)

I can't count how many times I use this construct in my code every day.
It's a right pain in the ass to always have to write out the long-winded
intialiser for pend, so I'm considering switching to initialising pend
as follows:

int const *const pend = *(&my_array+1);

1) my_array is an int[X]
2) &my_array is an int(*)[X]
3) &my_array+1 is the address of the non-existant array located after
the current one.
4) *(&my_array+ 1) decays to the address of the first element in the
non-existant array after the current one, which is also the "pend"
address for the array that actually exists.

It's a hell of a lot shorter to write, and also I think it's a little
less vulnerable to typos because you'll most likely get a type mismatch
if its written wrongly.

Anyway, just wondering what people think of the alternative. Saves me
that little rush of pissed-off-ness every time I've to write out the
tedious sizeof thing.

(Oh and by the way, I wouldn't use a macro such as ARRLEN(my_array)
because then I'd have to worry about including the necessary header
file... which is also the reason why I don't use NULL.)

--
Tomás Ó hÉilidhe
.



Relevant Pages

  • Re: Neatest way to get the end pointer?
    ... intialiser for pend, so I'm considering switching to initialising pend ... address for the array that actually exists. ... tedious sizeof thing. ... Free games and programming goodies. ...
    (comp.lang.c)
  • Re: Neatest way to get the end pointer?
    ... p == pend, so the address is not dereferenced by p ... However, OP _does_ dereference it. ... element in the non-existant array after the current one, ... The last expression will decay to an int * when used in the ...
    (comp.lang.c)
  • Re: Neatest way to get the end pointer?
    ... At no stage is pend dereferenced; ... However, OP _does_ dereference it. ... element in the non-existant array after the current ... of an array object that does not exist. ...
    (comp.lang.c)
  • Re: Neatest way to get the end pointer?
    ... p == pend, so the address is not dereferenced by p ... However, OP _does_ dereference it. ... element in the non-existant array after the current one, ... The last expression will decay to an int * when used in the ...
    (comp.lang.c)
  • Re: Neatest way to get the end pointer?
    ... while (pend!= p); ... However, OP _does_ dereference it. ... element in the non-existant array after the current one, ... computing &my_array+1 is invalid. ...
    (comp.lang.c)