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
15
17
12
The bagel temperatures are
17
22
41
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