是否使用 char 未定义行为访问数组元素? [英] Is accessing an array element using a char undefined behaviour?
问题描述
由于不清楚什么是未定义行为,什么不是 C 语言,我想知道使用 char 访问数组元素是否是未定义行为.例如:
Since it's not clear what's undefined behaviour and what's not in C, I'm wondering if accessing an array element using a char is or not undefined behaviour. For example:
char c = 'A';
int a[3000];
printf("%i\n", a[c]);
我知道实际上字符和整数在某种程度上是可以互换的,但我仍然不确定.
I know that actually chars and ints are somehow interchangeable, but still, I'm not sure.
推荐答案
是否使用 char 未定义行为访问数组元素?
Is accessing an array element using a char undefined behaviour?
这不是未定义的行为.它的工作方式类似于另一种整数类型.然而,char
的数值可能令人惊讶地为负数.
It is not undefined behavior. It works like another integer type. Yet the numeric value of a char
may surprisingly be negative.
char
与 signed char
或 unsigned char
具有相同的范围.它是实现定义的.
A char
has the same range as signed char
or an unsigned char
. It is implementation defined.
使用 c
作为索引是可以的,如果提升的索引加上指针会产生一个有效的内存地址.详细信息:char
将被提升为 int
,或可能的 unsigned
.
Using c
as an index is fine, if the promoted index plus the pointer results in a valid memory address. Detail: A char
will be promoted to int
, or possible unsigned
.
如果 c
为负值,则以下可能是一个问题.在 OP 的情况下,使用 ASCII 编码,'A'
的值为 65,因此 0 <= 65 <;3000
.@Joachim Pileborg
The following is potentially a problem had c
had a negative value. In OP's case, with ASCII encoding, 'A'
has the value of 65, so it does not have a problem as 0 <= 65 < 3000
. @Joachim Pileborg
char c = 'A';
int a[3000] = { 0 };
printf("%i\n", a[c]); // OK other than a[] not initialize in OP's code.
这篇关于是否使用 char 未定义行为访问数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!