我有一个简单的程序是这样的:通过添加'0'将整数转换为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的简化版本。
将程序的输出输出到'hexdump -C'并查看输出。字符'0'的Ascii值是'48'(dec),通过在'48'上加2得到ascii值'50',即2的字符。 –
这与Ascii代码有关。如果你声明'int numbers [] = {'1','2','3','4','5'};'那么你不需要添加''0''。 – tivn