0

This is the source code

#include<stdio.h>
void main()
{
int *p,a=5;
p=&a;
scanf("%d",p);
printf("%d\t",*p);
printf("%d",a);
}

How can we accept an address of a pointer?.Cuz it has the address of variable 'a' already.There are no errors shown by the compiler. Also,i'm not able to understand the output.

output:(if my input is 45)

45   45 

2 Answers2

1

Your pointer is also a variable like a and has it's own address. You can access it by saying &p. But you say scanf("%d", p); so it is accessing pointer's pointing address.

EDIT: if you want to print pointer's address you can use printf("%p\n",(void *) &p);

cokceken
  • 2,068
  • 11
  • 22
0

You can access pointer itself by its address &p

int pa;
int *p;
scanf("%d", &pa);

p = (int*) pa;

printf("%p\t", p); // printing pointer stored address (got from input)
printf("%d\n", (void *) *p); // printing value stored in address stored in p, of course would be segfault in case of invalid address

Also use it with caution, its unportable and may resulting undefined behavior. it may work on 32bit machines because of int and int* have same length of bits but for other CPU's may not work.

e.jahandar
  • 1,715
  • 12
  • 30
  • 4
    What's the idea behind doing `scanf("%d", &p);`? In fact it provokes undefined behaviour, because `d` is defined to scan `int`s only. – alk Dec 15 '16 at 08:05
  • I agree that its not portable, but in fact on 32 bit machine int and int* have same length, so we can copy contents of int to int*. The int could store the address of something but could not dereference it. – e.jahandar Dec 15 '16 at 08:12
  • 2
    Cast to `(void *)` before printing an address. This is required by the Standard. – ad absurdum Dec 15 '16 at 08:21