在 cpp 中,可以使用数组声明作为 typename array[size]; 或 typename *array = new typename[size]; 其中数组的长度为“大小”,元素的索引从“0”到“大小-1”这里我的问题是我是否允许访问索引> =大小之外的元素。
所以我写了这个小代码来检查它
#include <iostream>
using namespace std;
int main()
{
//int *c; //for dynamic allocation
int n; //length of the array c
cin>>n; //getting the length
//c = new int[n]; //for dynamic allocation
int c[n]; //for static allocation
for(int i=0; i<n; i++) //getting the elements
cin>>c[i];
for(int i=0; i<n+10; i++) //showing the elements, I have add up 10
cout<<c[i]<<" "; //with size to access the memory I haven't
//allocated for
return 0;
}
结果是这样的
2
1 2
1 2 2686612 1970422009 7081064 4199040 2686592 0 1 1970387429 1971087432 2686700
程序不应该崩溃而是给出垃圾值。对于这两种分配方法,它给出了相同的结果。它会产生更多难以检测的错误。它与我正在使用的环境或编译器或其他任何东西有关吗?
我在 Windows 8.1 上使用具有 TDM-GCC 4.8.1 编译器的代码块 IDE
提前致谢。