且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否使用 char 未定义行为访问数组元素?

更新时间:2023-11-10 19:43:34

是否使用 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.

charsigned charunsigned 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 .@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.