动态数组索引越界问题

1、在C++中,可以采用几种不同的方法创建一个某种类型T的对象的数组。3种常用的方法如下:

#define N 10 //数组的长度N在编译时已知
  T static_array[10];

  int n = 20; //数组的长度n是在运行时计算的
  T* dynamic_array = new T[n];

  std::vector vector_array; //数组的长度可以在运行时进行修改

当然,我们仍然可以使用calloc()和malloc()函数,并且这样的程序仍然能够通过编译并顺利运行。但是,混合C和C++代码并不是良好的编程思路,除非由于依赖遗留的C函数库的原因而必须这样做。不管我们用什么方法分配数组,都可以用一个无符号整数作为索引访问数组中的元素。

const T& element_of_static_array = static_array[index];
const T& element_of_dynamic_array = dynamic_array[index];
const T& element_of_vector_array = vector_array[index];

如果我们提供一个大于或等于数组长度的索引值,会发生什么情况呢?以上的代码都会安静的返回垃圾数据。如果

你可能感兴趣的:(C++基础知识,动态数组,索引越界,vector)