Re: More on pointers to pointers.



Dave Vandervies wrote:
In article <1143773007.173184.158940@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
Chad <cdalten@xxxxxxxxx> wrote:
<snip>
I guess even more to the point, why is this legal?
arg = &(*ptr) ;

ptr gets converted to a pointer to its first element, and then you follow
that pointer, so the expression inside the parens identifies an object
of type pointer to char.
Then the & operator gives you a pointer to that object, with type
pointer to pointer to char. Since this is the same type of the object
you're storing it into, this works with no problems or complaints from
the compiler.

(This one is actually a special case of a more general rule: since & (get
pointer) and * (follow pointer) are inverse operations, saying "&(*p)"
will always give you the same value as just saying "p" for any pointer p,
and "*(&x)" will always give you the same object as just saying "x".)

To be precise in a way that doesn't really matter but is still notable: this is a direct consequence of how & is defined. In particular, the standard guarantees that "&*p" is equivalent to "p" for *any* pointer p, even if p is invalid, because the subexpression "*p" is not evaluated.

Some compilers actually get this wrong if optimization is not turned on, and will insert evaluation of the pointer.

S.
.



Relevant Pages

  • Re: TEA Implementation
    ... The second argument should be a pointer to pointer to ... It should be the address of a pointer to char. ... compiler won't even accept it at all. ... Seems like a rather confusing way of writing ...
    (comp.lang.c)
  • Re: large files: when ubiquitous?
    ... the pointer might be into shared ... compiler will make optimizations giving unexpected ... same with and without optimization, ... to a char pointer type or changing p to be a char ...
    (comp.os.linux.development.system)
  • Re: lvalue assignment error
    ... > char *sstrdup ... convert the char pointer to a void pointer automatically, no cast ... compiler is forced to assume that it returns an int. ...
    (comp.lang.c.moderated)
  • Re: Keil c51 interprets &Array as Array. Is that normal?
    ... Yes it is a pointer to an array of 10 chars. ... but the compiler is well aware of it ... char a; ... Need to learn how to apply control theory in your embedded system? ...
    (comp.arch.embedded)
  • Re: large files: when ubiquitous?
    ... > optimizations performed by the compiler. ... > pointer to a float, and another pointer to a long, the ... void* is a contractural promise that it's 4-aligned. ... If we pass char* instead to f, then we would be implictly saying that we ...
    (comp.os.linux.development.system)