Monday, February 27, 2012

printf and types

This blog started as a notepad for lessons learnt. My career requires me to live in fluffy architect land (it's like real life except there's lots of whiteboards and clouds) and sometimes I struggle to remember how to solve hands-on problems. I started by keeping a notepad. Several lost notepads later, I upgraded to the  Evernote online notepad service. I like to keep a unique password for each online service. Having a unique password means that if a single site is compromised, your credentials on other sites remain secure. To make a long story short, I started blogging my problems so I wouldn't have to recall a password to access the knowledge that should have been in my head in the first place.

This blog post is about a basic printf problem in C which is different from the usual virtualization/architecture/licensing content on this blog. Hey, this is my blog, I can write about anything I want: next blog post is all cake recipes! I'm learning C because I want a challenge and I'm sick of Java. I'm blogging about it so I can remember my mistakes and serve as a warning to others not to learn C. If several months have passed and this is the only blog post on C, you can assume I've given up and that you shouldn't learn C either.

Anyway, now it's time to spot the error in my code. The following code stores records the temperature of three bagels and stores them in array bagelTemperature.

bagelTemperature[0] = 15;
bagelTemperature[1] = 17;
bagelTemperature[2] = 12;

printf("The bagel temperatures are\n");
printf("%d\n", bagelTemperature[0]);
printf("%d\n", bagelTemperature[1]);
printf("%d\n", bagelTemperature[2]);

printf("The bagel temperatures are\n");
printf("%x\n", *(bagelTemperature));
printf("%x\n", *(bagelTemperature+1));
printf("%x\n", *(bagelTemperature+2));

will output

The bagel temperatures are
The bagel temperatures are

Why are the two bagel temperatures different?

Simple mistake: the type field in the second set of printf statements is incorrect. Replace the %x and %d and the bagel temperatures will be good. %d is for signed decimal integers and %x is for unsigned integers written with hexadecimal. If you don't select the correct type, your output might be different to what you expect. Until I realised the problem was with the type, I was scratching my head wondering if there was a problem with my pointer arithmetic.

No comments:

Post a Comment