I have a simple program, for example:
#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;
}
Compilation and launch give:
$ gcc -std=c11 -pedantic -Wall -Werror ex8_simple.c
$ ./a.out
$ name (before) = Mix
$ name (after) = Mx
This is not what I want. Then I dug up the question Save an integer value in an array of characters in C and changed the program as follows:
name[1] = '0' + numbers[1]; //replacing >> name[1] = numbers[1];
Then it works as I expected:
$ gcc -std=c11 -pedantic -Wall -Werror ex8_simple.c
$ ./a.out
$ name (before) = Mix
$ name (after) = M2x
I don’t understand what is happening under the hoods, although the version other than the '0' + …one is really strange. Why is the string truncated in this “weird” way to Mx?
For reference, this is a simplified version of Exercise 8 from Learn C The Hard Way .
source
share