Get this pointer stuff over with, people

Todd P. Whitesel toddpw at tybalt.caltech.edu
Thu May 18 03:40:18 AEST 1989


(various posters, whose names do not matter wrote the quoted lines)
>[char *t, *p, *q]
>>>  t = p + q;
>>
>>But you haven't told us what this means!

Because C doesn't define a meaning. Now it COULD be that since p is the base of
an array of char, q is an offset which is obtained by q = t - p; this is easy
to do when you work in assembler since it is just a difference of addresses.

But the machine independence of C would like to hide the fact that 
char *t, *p, *q and int *t, *p, *q will produce different results for q when
q = t - p; also, when you use the [] array notation your integer index gets
multiplied by sizeof(int) or sizeof(char) or whatever is appropriate so why
bother using differences of pointers when the same idea can be expressed in
a machine (and data type) independent way that hides the size of the data
object (after all, portable C programs don't rely on sizeof unless they really
have to).

Since q is the offset into p to get t, and all three are the same type, then
q can be expressed as an integer times the size of the data type, so why not
use the integer? since you will always be working in units of the data type
if you're writing portably it is simpler to say q++ (q is an integer here)
instead of q += sizeof(char or whatever), q += 3 instead of q += 3*sizeof(etc).

In short, the operations on pointers (you can't add two pointers to get a
pointer and the like) are rigged so you will use integer indexes instead of
raw pointers to do things like offsets, all of which can be done with the index
notation anyway, if you set things up correctly.

Since adding a pointer to an integer requires converting the intger to an
"offset pointer" by multiplying it by the sizeof, and addition is commutative,
2["hello"] makes sense to the compiler because it translates this into
2+"hello" which is 2*sizeof(char) + *hello; to the compiler this addition of
addresses is ok. 

so in the above example the way to optimize the loop would be to find the
offset somehow (typecasting to int? Bleargh) and somehow convince the compiler
to accept your address (also Bleargh) so if you really need FAST code you may
as well use machine language (should have been an "address" data type that
was machine dependent but let you do these sort of optimizations. ah well)

Snide post of the week award goes to:
>				--Blair
>				  "Introducing N.O.C.W.A.P.: The National
>				   Organization of Code Writers for
>				   Addable Pointers."
pipe down, eh? Pointer arithmetic is one of the more beautiful and unique
aspects of C. It made no sense to me at first, either, because it was so
unfamiliar.

Todd Whitesel
toddpw @ romeo.caltech.edu
toddpw @ caltech.bitnet



More information about the Comp.lang.c mailing list