tags:

views:

381

answers:

3

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;

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);
+8  A: 

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.

Chris Jester-Young
and one needs to cast the pointers to `void *` in `printf()` with `%p` format.
Alok
@Alok: Yes, very good point. +1
Chris Jester-Young
+2  A: 

Here's a good printf reference for you.

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

jschmier
+5  A: 

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).

AndiDog
Good point about the funny quotes. Not sure the browser is to blame -- more likely using MS Word as a text editor. That'll definitely produce compiler errors, which may be the type of errors the OP is getting.
Dan