There are some facts about c you’re missing:
-
There’s no
string
datatype. A string is just a sequence ofchar
ending with a0
byte. What you use here is a string literal — the compiler translates it to an array ofchar
and automatically adds the0
at the end. -
An array when passed to a function is automatically converted to a pointer to its first element, so your
printf()
here gets a parameter of typechar *
.
With this in mind, your code is just undefined behavior: Your format string (%c
) tells printf()
to expect a char
, but it is given a char *
instead which is a completely different type and normally has a different size (e.g. 4 bytes on your typical i386 machine).
What will probably happen in practice is that printf()
will show the least significant byte of the address of your char
array, interpreted as an ASCII character. It will look random. But it could also just crash or do whatever else, it’s undefined …
For starters, always compile your c code with all compiler warnings enabled. Then you will get warnings about most things that might come out undefined or are dangerous for other reasons. In case you don’t understand a warning, google for it.
If you use gcc
, the way to do it is gcc -Wall -Wextra -pedantic
.