Rohit
Rohit

Reputation: 635

Understanding complex pointer and address-of operators using *&*&p in C

Can any one explain how the printf is printing hello in the following?

#include<stdio.h>

void main()
{
 char *p;
 p="hello";
 printf("%s",*&*&p);
}

I know that *&p...means value in p, i.e the address of string "hello". What is happening in the initial *&

Upvotes: 0

Views: 2285

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361682

As you said, *&p means p, that means the consecutive * and & cancels out. Hence *&*&p becomes p too.

And as @Kerrek said (in the comment) that *&p produces an lvalue, so you take its address again.


Note that your code is not standard conformant. main() must have int as return type. And you cannot assign "hello" to a non-const char*. It must be const char*. A standard conformant code would be this:

#include<stdio.h>

int main()
{
   const char *p = "hello"; 
   printf("%s",*&*&p);
}

Upvotes: 7

Richard Heath
Richard Heath

Reputation: 347

'*&' cancels each other. You are getting the address of p then dereferencing it again. So the end result will just be p.

Upvotes: 0

Claudiu
Claudiu

Reputation: 229541

&p is the address of p.

*p is the thing pointed at by the address p.

*&p is *(&p) the thing pointed at by the address &p - which is p itself (i.e., the thing pointed at by the address "address of p").

Thus it turns out that *&p is just p - the *& cancel each other out. You can repeat this: *&*&p will still be p. You can do this ad infinitum: *&*&*&*&*&*&*&*&*&p will also be p.

Upvotes: 1

Related Questions