use*_*119 -1 c memory arrays undefined-behavior
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
char element B
char element
char element
Run Code Online (Sandbox Code Playgroud)
根据我的理解,C\C++ 实际上并没有对数组进行任何边界检查。这取决于操作系统以确保您正在访问有效的内存。所以这是未定义的行为。
但是在这里我可以在不同的机器上看到相同的行为。即程序不会随时崩溃。