Code :: Blocks does not print the pointer value

0

I developed a code in C to print the value and address of the variable x using a p pointer, but Code :: Blocks does not print the values.

    #include <stdio.h>
    #include <conio.h>

    int main()
    {
    int x=2;
    int *p;
    p = &x;

    printf("O valor de X e: %p\n", *p);

    printf("O valor de X e: %d\n", p);

    return(0);

    }
    
asked by anonymous 19.08.2018 / 17:57

2 answers

1

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.

    
19.08.2018 / 18:25
0
int x=5;
int *p;
p = &x;
printf("O valor de X e: %d\n", *p);
printf("O valor de X e: %d\n", p);

The first printf() prints the value of x, the second prints the address of the pointer.

All your code is fine, this 'c' is 12 in hex.

    
19.08.2018 / 18:03