Search code examples
cchar

Converting an integer to char by adding '0' - what is happening?


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.


Solution

  • Each symbol has an numeric representation, so basically each char is a number. Here is the table of characters and its values.

    enter image description here
    (source: asciitable.com)

    So, in your code name[1] = numbers[1];, you assign name[1] to 2, which is equal to symbol STX in the ASCII table above, which is not a printable character, thats why you get that incorrect output.

    When you add '0' to your name[1], it is equal to add 48 to 2, so the symbol with the number 50 is '2', that's why you get that correct output.