我正在为包含struct
s的二维数组的类测试一些代码。
WrapperClass x;
SomeStruct try1 = x.at(0, 0);
SomeStruct try2 = x.at('a', 1);
SomeStruct array[] = {try1, try2};
// There were originally 3 of these test variables above, but I forgot to
// change the loop upper bound when I deleted one
for (int i = 0; i < 3; i++) {
// I added this line after noticing the non-error
std::cout << &array[i] << '\n';
std::cout << array[i].property1 << '\n';
std::cout << array[i].property2 << '\n';
std::cout << array[i].property3 << '\n';
std::cout << "-\n";
}
return 0;
输出:
0x7ffdadface08
0
0
0
-
0x7ffdadface14
0
0
0
-
0x7ffdadface20
0
0
0
为什么这段代码不会出现&#34;访问越界&#34;错误或什么?我只在数组中创建了2个结构体;为什么突然有第三个我能自由安全地进入?
答案 0 :(得分:3)
因为它是未定义的行为,任何事情都可能发生,包括没有立即错误。我建议你使用容器,例如由良好的调试编译器进行边界检查的向量。