How to use printf in C and what should my code print?

I'm new to C, and I'm trying to figure out what the printf method does. I have some code and I keep getting errors when I use% x, for example printf("a) %x\n", px);x% for hex, am I just using the wrong type here or is something else happening? What should print the code that I have below?

int x = 10;
int y = 20;

int *px = &x;
int *py = &y;

printf("a) %x\n", px);
printf("b) %x\n", py);

px = py;

printf("c) %d\n", *px);
printf("d) %x\n", &px);

x = 3;
y = 5;

printf("e) %d\n", *px);
printf("f) %d\n", *py);
+3
source share
3 answers

This works fine, no errors (except for incorrect quotes, that is, "instead of" ", but I think your browser did this).

Here is an example of your code output:

a) 22ff74
b) 22ff70
c) 20
d) 22ff6c
e) 5
f) 5

And here is the explanation

int x = 10;
int y = 20;

int *px = &x;
int *py = &y;

// You're printing out the pointer values here, which are the memory addresses of the
// variables x and y, respectively. Thus this may print any reasonable number within
// the stack memory space.
printf("a) %x\n", px);
printf("b) %x\n", py);

// Both pointer now point to y...
px = py;

// ... so this will print the value of y...
printf("c) %d\n", *px);

// ...and this will print the address of px, which will probably but not necessarily
// be the (memory address of y - 4) because the stack grows down and the compiler
// allocates space for the variables one after another (first y, then px).
printf("d) %x\n", &px);

x = 3;
y = 5;

// Remember that both px and px point to y? That why both *px and *py resolve to
// the value of y = 5.
printf("e) %d\n", *px);
printf("f) %d\n", *py);

"% p" "% x", ( , ).

+5

(%x, %d ..) . , (px, py &px, *px *py) %p .

+8

Source: https://habr.com/ru/post/1733305/


All Articles