【发布时间】:2020-07-21 06:47:54
【问题描述】:
#include <stdio.h>
#define CHAR_ROW_SIZE 4
int charTable[CHAR_ROW_SIZE ][2] = {
{'X', 'Z'},
{'J', 'L'},
{'F', 'C'},
{'A', 'B'}
};
int main()
{
printf("char element %c\n", charTable[3][1]); //fine
printf("char element %c\n", charTable[3][8]); // accessing 4th row's 9th element which is not valid
printf("char element %c\n", charTable[85][0]);// accessing 86th row's first element which is not valid
return 0;
}
输出:
char element B
char element
char element
据我了解,C\C++ 实际上并没有对数组进行任何边界检查。这取决于操作系统来确保您访问的是有效内存。所以这是未定义的行为。
但在这里我可以看到在另一台机器上的相同行为。即程序不会随时崩溃。
【问题讨论】:
-
Undefined Behavior 就像一盒巧克力——你永远不知道你会得到什么......见:Undefined, unspecified and implementation-defined behavior和What is indeterminate behavior in C++ ? How is it different from undefined behavior? 和nasal demons: n.
标签: arrays c memory undefined-behavior