通过添加 '0' 将整数转换为 char - 发生了什么?

标签 c char

我有一个像这样的简单程序:

#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;
}

编译运行给出:

$ gcc -std=c11 -pedantic -Wall -Werror ex8_simple.c
$ ./a.out
$ name (before) = Mix
$ name (after) = Mx

这不是我想要的。然后我挖出了问题 Store an integer value in a character array in C并像这样更改了程序:

name[1] = '0' + numbers[1];  //replacing  >> name[1] = numbers[1];

然后它按照我的预期工作:

$ gcc -std=c11 -pedantic -Wall -Werror ex8_simple.c
$ ./a.out
$ name (before) = Mix
$ name (after) = M2x

虽然我不明白引擎盖下发生了什么,尤其是没有 '0' + … 的版本真的很奇怪。为什么字符串以那种“奇怪”的方式被截断为 Mx

作为引用,这是 exercise 8 of Learn C The Hard Way 的简化版本.

最佳答案

每个符号都有一个数字表示,所以基本上每个字符都是一个数字。这是字符表及其值。

enter image description here
(来源:asciitable.com)

因此,在您的代码 name[1] = numbers[1]; 中,您将 name[1] 分配给 2,这等于上面 ASCII 表中的符号 STX,它不是可打印字符,这就是为什么你会得到不正确的输出。

当您将 '0' 添加到您的 name[1] 时,它等于 将 48 添加到 2,因此带有数字 50'2',这就是您获得正确输出的原因。

关于通过添加 '0' 将整数转换为 char - 发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30029294/

相关文章:

c - 基本的 C 头文件语法

c - 为什么 "char"变量中可以存储多个字符?

c++ - 拆分并从字符串转换为字符数组

Java:没有空格的空字符

c - 使用C返回数组

python - python : input and output arrays 的 swig 类型映射

c - MMAP读写文件

c - 指向结构和打印的指针

c - 连续调用 recvfrom() 丢失数据?

c - 将 char[] 写入数组