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

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 .

+5
source share
3 answers

, . .

enter image description here
(: asciitable.com)

, name[1] = numbers[1]; name[1] 2, STX ASCII , , .

'0' name[1], add 48 to 2, 50 '2', .

+8

, .

. .

  • name[1] = chars[1];
    

name[1] a chars[1] i. , o/p - Mix.

  • name[1] = numbers[1];
    

name[1] a numbers[1] 2 ( '2'), . ​​ (# note) , Mx.

 name[1] = '0' + numbers[1];

ASCII '2', '0'. , character '2' .

:

yout int char 0-9, '0',

int numbers[] = {'1', '2', '3', '4', '5'};

name[1] = numbers[1];

/.


: , C 0.

# . . ASCII.

+4

: name[1] = numbers[1]; int char name[1], int numbers[1] Ascii char char name[1].

When you execute name[1] = '0' + numbers[1];, then the number (2) is added to the ascii code of the number 0, and so you get the actual number. The ascii code 0is 48, add 2 to it, you will get 50which is the ascii code for 2.

Earlier, when you assigned only name[1] = numbers[1];, without 0, a char was printed with ascii code 0. Since this is not a valid printed character, nothing was displayed (in my car, it was displayed as some kind of strange emoticon).

+2
source

All Articles