PDA

View Full Version : & and handles


sealfin
2002.06.04, 03:52 AM
which of these ('one' or 'two') would '&(*one)->two' be accessing? (must get a better C book) ignore that the pointer/handle is never malloc()'d e.t.c.


struct original_struct
{
int two;
}
*original;


//
//
void some_function(original_struct **one)
{
scanf("%d", &(*one)->two);
}

CMagicPoker
2002.06.04, 03:56 AM
Im not sure.
With things like that, use parenthesis when you're not sure, example:

scanf("%d", &((**one).two));


If it compiles right, it is right ;-)

wadesworld
2002.06.04, 11:20 AM
which of these ('one' or 'two') would '&(*one)->two' be accessing?

Look closely at it, and read it from the inside out:

(*one) = dereferences one, leaving us with pointer to an original_struct.

(*one) ->two points us to the value of the two field of the struct

&(*one)->two gives us the address of the two field of the struct

Note that the -> operator binds more tightly than the & operator. If it didn't, you'd have:

&(*one) giving us the address of the pointer to the original struct

&(*one)->two which likely wouldn't work since we're basically pointing into random memory. If it did work, it'd point to garbage.

Thus, the suggestion of setting up parenthesis to get exactly what you want is correct:

&((*one)->two)

Even though the other works, this version makes it easy to understand exactly what will happen without having to remember or look up precedence rules.

If it compiles right, it is right ;-)

Oh, if only that were true. You can create any number of pointer combinations which will compile, but are wrong.

Wade