1

i'm new learning C, and learning pointer right now,i study from this website, but this code give me an error : pointer.c: In function ‘main’: pointer.c:6:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=] printf("Address: %d",&var); //Notice, the ampersand(&) before var.

i compile it with : gcc -o pointer pointer.c

/* Example to demonstrate use of reference operator in C programming. */
#include <stdio.h>
int main(){
int var = 5;
printf("Value: %d\n",var);
printf("Address: %d",&var);  //Notice, the ampersand(&) before var.
return 0;
}

http://www.programiz.com/c-programming/c-pointers

mas bro
  • 312
  • 1
  • 12

3 Answers3

2

You're trying to print the address of var as if it was a signed integer, which it isn't. It's a pointer, and might have a different size than an integer.

Passing values of mismatching types to printf() invokes undefined behavior, which is why the compiler is issuing a friendly warning.

You should use %p to format it, and cast the value to (void *) to comply with the C standard:

printf("Address: %p\n", (void *) &var);
unwind
  • 391,730
  • 64
  • 469
  • 606
2

Please use correct format specifiers for each data type. Addresses are specified by %p.

jada12276
  • 129
  • 8
1

It's better if you use %p to print a pointer. From the specification:

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

Don't forget the cast: printf("Address: %p\n",(void*)&var);

Paulo
  • 1,458
  • 2
  • 12
  • 26