0

I know that & gives the address of a variable. However what does & do on a pointer itself?

#include <stdio.h>

int main()
{
    int a = 10;
    int *p = &a;
    printf("%p" , p);
    printf("%d" , *p);
    printf("%d" , &p);
}

can you explain what each of the statement does. Also not sure about the format specifier of &p.

user438383
  • 5,716
  • 8
  • 28
  • 43
eyah
  • 111
  • 1
  • 8
  • In the last one `&p` outputs the location of the pointer variable itself. But you used the wrong format specifier `%d`, it should be `%p`. – Weather Vane Dec 25 '21 at 16:04
  • 1
    It does the same thing it does on any other type - it returns its address, in this case `&p` gives you a `int**` – UnholySheep Dec 25 '21 at 16:05

2 Answers2

1

Pointer p is also a variable and & operator, when used with pointer variable, gives address of that pointer variable. To print pointer use format specifier %p and, ideally, the argument passed to printf() should be pointer to void. So, you should do

    printf("%p" , (void *)p);
    .....
    printf("%p" , (void *)&p);

can you explain what each of the statement does.

This statement

    printf("%p" , p);

will print address of variable a. [The argument p should be type casted to (void *).]

This statement

    printf("%d" , *p);

will print value of variable a.

In this statement, the format specifier used is wrong, it should be %p

    printf("%d" , &p);
            ^^ 
             |
             +--> %p

when you give correct format specifier %p, it will print address of variable p. [The argument &p should be type casted to (void *).]

H.S.
  • 11,654
  • 2
  • 15
  • 32
0

It is doing what you have written yourself

I am new to c and know that & gives the address of a variable.

So the expression &p gives the address of the variable p declared like

int *p = &a;

p is an ordinary variable that has the type int *.

To make it more visible you could introduce a typedef name like for example

typedef int * T;

Then the declaration of the pointer p will look like

T p = &a;

So the expression &p is the address of the variable p the same way as the expression &a is the address of the variable a.

Pay attention to that you have to use the conversion specifier %p instead of %d with a pointer

printf("%p\n" , ( void * )&p);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335