pointer increment

Brian Bainter brian at trantext.UUCP
Sun Aug 13 05:10:39 AEST 1989


In article <484 at eagle.wesleyan.edu>, dkonerding at eagle.wesleyan.edu writes:
> 
>         Hi folks.  I'm a confused beginner C programmer who'd like to
> understand pointer variables a bit better.  I have a small program.  I've done
> the following:  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?

You must realize what you are incrementing here. Since you are working with
an integer pointer here, you are incrementing the pointer to the next integer.
Since you seem to be working on a machine where integers are equivalent in
size to longs, your incrementation (is that a word?) of the pointer will place
you four bytes down the road (at the next integer position).

If you want a pointer to increment to the next byte, you must use a character
pointer of type "char *". Since character arrays are built on one byte
increments, incrementing a character pointer will place the pointer at the
next byte or character position.

The same holds true with any kind of pointer. If you have a pointer to a
structure of say 35 bytes, every time you increment the pointer, it will point
to the next structure of 35 bytes (unless you are working on a CPU similar
to the 68x00 family where odd word boundaries are not allowed which may place
each structure every 36 bytes apart).

The main thing to remember with pointer arithmetic is what type of variable
am I pointing to and how much memory does that variable take up, and when I
increment a pointer to that variable I will be incrementing the pointer by the
number of bytes the variable takes up times the number I am adding to the
pointer.

The same holds true with I believe any arithmetic operation done on a pointer
(add, subtract, multiply, devide, etc.).

Hope this helps,
-- 

Brian R. Bainter  KA7TXA
gatech!kd4nc!trantext!brian or
gatech!tomcat!brian



More information about the Comp.lang.c mailing list