pointer increment

Doug Gwyn gwyn at smoke.BRL.MIL
Sat Aug 12 17:35:17 AEST 1989


In article <484 at eagle.wesleyan.edu> dkonerding at eagle.wesleyan.edu writes:
>  int *ptr;
>        Now, say I make ptr=1000 or hex 3e8.  I want to add one to the ptr, to
>make it point to 1001, or hex 3e9.  Every time I do a ptr=ptr+1, it becomes
>3ec.  How can I simply increment ptr by one?

Wu!  (If you're not familiar with Zen: that means you should unask your
question.)

C pointers are more abstract than machine storage addresses, and once
you properly grok them (look up "grok" in "Stranger in a Strange Land"),
they more naturally lend themselves to expressing object reference than
raw untyped addresses would.  If you're having to fight them, it's
probably a sign that you need to improve your understanding of them.

Except under extremely unusual circumstances, which as a C beginner
you are probably not faced with, proper use of pointers REQUIRES that
you not even consider what "numerical values" they are supposed to
have.  If you have a pointer to one of a contiguous series (i.e. an
array) of data each of which has type int, and you wish to make the
pointer point at the next member of the array, express that by
"adding one" to the pointer.  The meaning of "adding N" to a
pointer-to-a-whatever is to produce a pointer-to-the-whatever-N-
whatevers-farther-along-the-array.  Forget about machine address
arithmetic; of course there must be some going on behind the scenes,
but you're not supposed to consider how it's accomplished.

If you wish to access individual members of an array of bytes, use a
pointer-to-char instead of pointer-to-int.  In C, a char is a byte.
(A byte need not be 8 bits, although that is the size most commonly
encountered.)

If, instead of dealing with nice, regular arrays, you're really
trying to access a "misaligned" int datum using a pointer to an
aligned int as a starting point, then you need to convert the original
pointer-to-int to a pointer-to-char (-byte) to do the bytewise pointer
arithmetic, then convert it back again afterward.  This series of
operations cannot be made to work on some computer architectures.
(It is expressed by
	ptr = (int*)((char*)ptr + 1);	/* NON-PORTABLE */
which does as I just said.)  Be sure that you really need to do
this; in many years of varied C programming I've rarely needed to
do anything like that.



More information about the Comp.lang.c mailing list