0

I try to print the value of address and it generates an error.

int main()
{
    int arr[] = {10,20,30,40,50,60};
    int *ip;
    ip=&arr[3];
    printf("%u",ip);

    return 0;
}
Antwane
  • 20,760
  • 7
  • 51
  • 84
Shubham Malik
  • 15
  • 2
  • 4
  • 1
    What is the error you get? – lenz Aug 31 '15 at 12:54
  • 1
    Also, I'm not sure this has anything to do with Ubuntu... Consider retagging your post to get the proper audience. – lenz Aug 31 '15 at 12:54
  • 1
    @lenz stack.c:9:1: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=] printf("%d",ip); – Shubham Malik Aug 31 '15 at 12:57
  • I don't see how anyone can answer or comment on this question without explaining that the value of a pointer **is the address** for the object it points to. That seems to be the breakdown in understanding in this case. `%p` is simply the format specifier that allows you to see it. – David C. Rankin Aug 31 '15 at 13:32

1 Answers1

6

As noted the value of pointer is the address of the object to which it points. You print it using:

printf("%p",(void*) ip);

If you are interested in the value of the object the pointer points to - you need to dereference it, and then use in this case %d format specifier:

printf("%d",*ip);
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
  • 2
    @jpw:that was typo. I guess cast is needed because %p expects pointer of type void. – Giorgi Moniava Aug 31 '15 at 13:10
  • 2
    @jpw: yes %p format requires an argument of type void*. see this http://stackoverflow.com/questions/5286451/how-to-print-variable-addresses-in-c & http://stackoverflow.com/questions/20374880/print-the-memory-location-of-a-variable-or-pointer. – Destructor Aug 31 '15 at 13:12