pointer increment

John Mundt john at chinet.chi.il.us
Sat Aug 12 22:37:48 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?


It is doing exactly what K & R want it to do.  When you do pointer
arithmetic, your addition is scaled by the size of the object the 
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pointer points to.  You must have a 4 byte int on the machine you are
using, since making ptr one larger caused it to point to the next int.

For example, if you had an array of pointers starting at memory location
1000, you'd have this:

1000+
0   4   8   12  16  20  24  28  32  36  40  44  48  52  56
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1st 2nd 3rd 4th 5th 6th 7th 8th 9th etc

*ptr would have the value held at 1000, *(ptr + 1) would hold the
value at 1004, *(ptr+2) the value at 1008, etc.

If you had made ptr a pointer to char, as in

char *ptr;

then doing ptr = ptr + 1; would give you 1001, since the size of a
char is one byte.

Alternatively, if pointer was a pointer to a structure

struct foo {			/* this structure is 40 bytes long */
	char foo1[20];
	char foo2[20];
} ary[2];

struct foo *ptr = &ary[0];	/* make ptr point to first ary */
				/* which we will assume as at 1000 again */

then ptr = ptr + 1 would equal 1040, since stepping ptr by one
moves it from the first structure to the second, which is what
we want to do. 
-- 
---------------------
John Mundt   Teachers' Aide, Inc.  P.O. Box 1666  Highland Park, IL
john at chinet.chi.il.us
(312) 998-5007 (Day voice) || -432-8860 (Answer Mach) && -432-5386 Modem  



More information about the Comp.lang.c mailing list