Code:: Blocks does not print pointer value

I developed a code in C with the purpose of printing the value and address of the variable x using a pointer p, 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);

    }
Author: Maniero, 2018-08-19

2 answers

Do not use conio.h, although in this case you do not need to. And if you're an IDE with a bad compiler (Dev-c++), stop doing this. Alias Code:: Blocks does nothing in executing the code itself, understand who is who in programming .

From what I understand the first you want to print the address of the memory where is the X since you used %p, and the Second wants to print the value of X. Then you have to arrange the text to give a correct information.

Then one problem is that it's reversed. p is already a memory address, so just use it in the first one. The second one wants the value and takes it indirectly by the variable p which is an address, so now you have to do the reverse operation you had done to take the address of X, then you have to do what is called dereference, which is done with the operator *. *P means " take the value that is at the address of p".

I put a (void *) because good compilers with the correct configuration it 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), at 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 working on ideone. And no repl.itd. Also I put on GitHub for future reference .

See more at What is the meaning of the "&" (and commercial) operator in the C language? and Operator & and * in functions .

 1
Author: Maniero, 2020-07-30 19:22:19
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 pointing address.

All your code is fine, that ' c ' is 12 in hexadecimal.

 0
Author: Fábio Morais, 2018-08-19 16:56:24