开发者

How to use printf in C and what should my code be printing out?

I am new to C and I am trying to figure out what the printf method does. I have this little bit of code and I keep getting errors when I use the %x for example printf(“a) %x\n”, px); x% is for hex, Am i just using the wrong type here or is something else going on? what should the code I have below be printing out?

int x = 10;
int y = 20;

开发者_Go百科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);


Using integer formats (%x, %d, or the like) for printing pointers is not portable. So, for any of the pointer ones (px, py, and &px, but not *px and *py), you should be using %p as your format instead.


It works perfectly well, no errors (except for the wrong quotes, i.e. “” instead of "" but I guess that's what your browser did).

Here's an example output of your code:

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

And here the explination

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's why both *px and *py resolve to
// the value of y = 5.
printf("e) %d\n", *px);
printf("f) %d\n", *py);

But anyway, for pointer you should usually use the "%p" format specifier instead of "%x" because that's for integers (which can be of different size than a pointer).


Here's a good printf reference for you.

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜