简体   繁体   English

为什么 char 不能工作但 int 可以

[英]Why can't char works but int does

char array[]= {1,2,3,4,5,6,7,8,9,1,2,3,6,7};
printf("%c\n", array[5]);

This returns " ".这将返回“”。 Nothing but when I change the char to int it prints "5".但是当我将 char 更改为 int 时,它会打印“5”。 I tot char can accept numbers from -128 to 127?我 tot char 可以接受从 -128 到 127 的数字吗?

int array[]= {1,2,3,4,5,6,7,8,9,1,2,3,6,7};
printf("%i\n", array[5]);

When you print the char , C assumes the value stored is supposed to represent ASCII encoded text.当您打印char ,C 假定存储的值应该表示ASCII编码文本。 Accessing array[5] yields the value 6 , which corresponds the ASCII value ACK .访问array[5]产生值6 ,它对应于 ASCII 值ACK This character is not printable, which is why you see no output.此字符不可打印,这就是您看不到输出的原因。

The character 6 is represented by the ASCII value 54 .字符6由 ASCII 值54 To produce this value, use the char literal '6' .要生成此值,请使用char文字'6'

For example, try initializing your array as:例如,尝试将数组初始化为:

char array[]= {'1','2','3','4','5','6','7','8','9','1','2','3','6','7'};

This will result in the behavior you expect.这将导致您期望的行为。

Alternatively, you can print the character as a formatted integer by using the flag %i in place of %c in your first snippet.或者,您可以通过在第一个代码段中使用标志%i代替%c将字符打印为格式化整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM