c ++计算跳跃范围

时间:2014-03-08 22:35:58

标签: c++

这里发生了什么?

标题文件:

// .h file
public:
    typedef size_t size_type;
    static const size_type CAPACITY = 3;
private:
    value_type data[CAPACITY];
    size_type cursor;

实施档案:

// .cpp file
for (cursor = 0; cursor <= CAPACITY; ++cursor)
{
    data[cursor] = -1;
    std::cout << "cursorPos: " << cursor << std::endl;
}

输出:

cursorPos: 0
cursorPos: 1
cursorPos: 2
cursorPos: 3220176896

1 个答案:

答案 0 :(得分:5)

您正在访问data越界。它的大小为3,因此有效索引的范围为[0,2]。您正在访问范围[0,3]。

访问数组越界是未定义的行为。您正在写入数组结束后发生在内存中的任何内容。在这种情况下,它似乎会影响索引的值。但你甚至不能依赖这种可重复的行为。

这将是一种设置具有特定值的数组元素的惯用方法:

#include <algorithm> // std::fill
#include <iterator>  // std::begin, std::end, C++11 only

std::fill(std::begin(data), std::end(data), -1); // C++11
std::fill(data, data + CAPACITY, -1);            // C++03
相关问题