I have a simple program like this:
#include <stdio.h>
int main(void)
{
int numbers[] = {1, 2, 3, 4, 5};
char chars[] = {'a', 'i'};
char name[] = "Max";
name[1] = chars[1];
printf("name (before) = %s\n", name);
name[1] = numbers[1];
printf("name (after) = %s\n", name);
return 0;
}
Compiling and running gives:
$ gcc -std=c11 -pedantic -Wall -Werror ex8_simple.c $ ./a.out $ name (before) = Mix $ name (after) = Mx
Which is not what I want. I then dug up the question Store an integer value in a character array in C and changed the program like this:
name[1] = '0' + numbers[1]; //replacing >> name[1] = numbers[1];
Then it works how I would expect:
$ gcc -std=c11 -pedantic -Wall -Werror ex8_simple.c $ ./a.out $ name (before) = Mix $ name (after) = M2x
I don't understand whats happening under the hoods though, especially the version without '0' + …
is really strange. Why is the string truncated in that "weird" way to Mx
?
For reference, this is a simplified version of exercise 8 of Learn C The Hard Way.