Do not use conio.h
, although in this case you do not even need to. And if you have a bad compiler IDE (Dev-C ++), stop doing this. Code :: Blocks does not do anything in the code execution itself, understand who's who in programming . p>
So I understand the first one you want to print the memory address where X
is since you have used %p
, and the second wants to print the X
value. So you have to sort the text to give correct information.
Then one problem is that it is inverted. p
is already a memory address, so just use it in the first. The second wants the value and indirectly get it for the variable p
which is an address, so now you have to do the inverse operation you had done to get the address of X
, then you have to do what is called derreferencing, which is done with the *
operator. The *P
means "get the value that is in the address of p
".
I put (void *)
because good compilers with the correct configuration prevent direct compilation, they force you to be explicit in what you are using to indicate that you are not confusing what you are sending. But it is possible not to use in certain circumstances (I did not use it in the Coding Ground, look there), under the risk of doing something wrong in more complex real code.
#include <stdio.h>
int main() {
int x = 2;
int *p = &x;
printf("O endereço de X e: %p\n", (void *)p);
printf("O valor de X e: %d\n", *p);
}
See running on ideone . And in Coding Ground . Also put it in GitHub for future reference .
See more at What the operator means "&" (and commercial) language in C? and Operator & and * functions.