Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

meaning of the * and & symbol [closed]

Tags:

c

pointers

What do the * and & symbols mean in this code:

#include<stdio.h>
main()
{
  char *p;
  p="hello";
  printf("%s\n",*&*&p);
}

What does the printf statement do in the above program? Specifically, what does *&*&p mean?

like image 536
Ghost Iscuming Avatar asked Aug 25 '12 06:08

Ghost Iscuming


2 Answers

These:

*&*&

Are redundant and you would never encounter such ridiculous code in a real project. The ampersand takes the address of p, and the asterisk * dereferences it to produce the original char*. Back and forth we go...

Think of it as:

*(&(*(&p)))

As an aside, your type-less signature for main won't cut it on modern compilers where a return type of int is no longer assumed.

like image 171
Ed S. Avatar answered Sep 26 '22 23:09

Ed S.


The printf will print the string "hello" because & is the addressOf operator which will return the address of the pointer followed by it and * is the valueOf operator which will return the value stored in the pointer address followed by it.

So in essence, the statement *&*&p will read

valueOf(addressOf(valueOf(addressOf(p))))

which will return the string "hello" which is stored in the actual location.

Hope this would help you!

like image 34
Xmindz Avatar answered Sep 24 '22 23:09

Xmindz