[OCLUG-devel] Re: [OCLUG] C - Pointer assignment

Chris Smith cbsmith at gmail.com
Mon May 23 12:05:41 PDT 2005


Again, replying to devel.

On 5/23/05, Joshua Robinson <joshua.robinson at paulsson.com> wrote:
> myPtr = *(array+1);
> 
> OR in a loop
> 
> while ( !array ) {
>     myPtr = *(array++)
> }

I'm going to go out on a limb here, but I'm guessing the myPtr is a
pointer to whatever type the array is made of. As such doing:

myPtr = *(array+1);

is possibly syntactically incorrect and almost certainly not what you
want to have happen. For example:

int array[3];
int* myPtr;

array[1] = 42; /* for clarity */
myPtr = *(array + 1);
do_something(*myPtr); /*almost certainly cause something bad to happen */

So, "array" evaluates as a pointer to the address of array Let's say
that the address is 5000000 (in decimal). "array + 1" evaluates to a
pointer to the first element of that array, so that's a pointer to
5000004 (assuming int's are 32-bit). Now "*(array + 1)" means to take
the value at the address pointed to by "array + 1". That's going to be
42 because of the line I tagged with "for clarity". Now, the problem
is, you're assigning it to myPtr, not the value pointed to by myPtr.
So, myPtr becomes a pointer pointing to address 42. That's probably
not what you intended, and more importantly is probably an invalid
address anyway.

-- 
Chris


More information about the OCLUG-devel mailing list