Tuesday, July 20, 2010

hunch confirmed

I guessed right.

Ok, so:

#include
#include
int main()
{
char c;
c = 'a';
printf("Hello %d\n",c);
return 0;
}

outputs "Hello 97".

If I change the %d to %s, it segfaults (Linux) or crashes (Windows). I tested this on both since there are sometimes differences in OS. The fancy IDE I'm using on Windows - Code::Blocks - warns me about using %s. I think %s is only for character arrays. How can I actually put a character though without using an array? Putchar()?

1 comment:

  1. The type descriptor you want is '%c':

    http://www.elook.org/programming/c/printf.html

    '%s' is used to display a null terminated string and when you use a char instead printf() spends all of its time looking for that terminating zero. Of course, it never finds it and the world explodes accordingly.

    ReplyDelete