Do not use conio.h
, even if you don’t have to. And if you have a bad compiler IDE (Dev-C++), stop doing this. Alias Code::Blocks does nothing in executing the same code, understand who’s who in programming.
From what I understand the first you want to print the address of the memory where the X
since you used %p
, and the second wants to print the value of X
. So you have to tidy up the text to give correct information.
There’s a problem that’s reversed. p
is already a memory address, so just use it in the first. The second wants the value and catch it indirectly by the variable p
which is an address, so now you have to do the reverse operation you had done to get the address of X
, then you have to do what’s called derreferenciar, which is done with the operator *
. The *P
means "take the amount that is in the address of p
".
I put a (void *)
Because good compilers with the right configuration prevents 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 in Coding Ground, look there), under 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);
}
Behold working in the ideone. And in the repl.itd. Also put on the Github for future reference.
See more in What is the meaning of the operator "&" (and commercial) in the C language? and Operator & and * in functions.
It "doesn’t print the values" or "doesn’t print the values you expected"? These are very different things, so I could clarify?
– Woss
He doesn’t print any valves
– Anne
@Anne better put what error codeblocks is displaying and if possible a print
– Fábio Morais
@Fábio Morais I think I understood why he is not returning any value because the variable x was not assigned to any value so it did not return anything. Assigns the value 2 in the variable x it returned the memory address and the value 00000002, but when I change the value to 12 for example it keeps returning the value 2. I tried using fflush(stdin) but could not solve
– Anne
Instead of %p use %d, as when making the printf of
*p
will print the value of x. Clearing the buffer in this case is irrelevant– Fábio Morais
That question is very confusing, that’s right, 'c' is 12 in hexadecimal....
– Fábio Morais
You can’t change the question, people have already answered what had been asked by invalidating the answers. I think better to see the [tour], here is not a forum is, the editing is not to change the content, just fix some problem or give additional information, what has in the question now is my answer. If you have another question regarding the answer you have given, ask a new question, do not change it. I put in the answer that works as expected and the extra information is not hitting. So I reverted to the original state.
– Maniero