C++ 数据变化无明显原因

标签 c++

我有以下方法:

void Polygon::expand() {
    int newSize = max * 2;
    printArray(array, current);
    Point* newArray = new Point[newSize];
    printArray(array, current);
    for (int i = 0; i <= current; i++) {
            newArray[i] = array[i];
    }
    delete[] this->array;
    array = newArray;
    max = newSize;
}

printArray 用于调试,也很简单:

void printArray(Point* array, int size) {
    cout << "array\n==========" << endl;
    for (int i=0; i<=size; i++) {
            cout << array[i] << ": " << array[i].getX() << ", " << array[i].getY() << endl;
    }
}

该方法试图扩展数组,它是类型Point* 的类成员。奇怪的是我在运行时得到的打印:

array
==========
(0,0): 0, 0
(1,1): 1, 1
(2,2): 2, 2
(3,3): 3, 3
array
==========
(0,0): 0, 0
(1,1): 1, 1
(2,2): 2, 2
(3,5.58294e-322): 3, 5.58294e-322

由于某种原因,数组中的最后一个 Point 发生了变化,即使我在打印之间没有触及它!知道是什么原因造成的吗?

最佳答案

当您从 0 开始编制索引时(如在 C 和 C++ 中),您会在小于 size 的位置停止。所以,做:

for (int i=0; i<size; i++) // not <= 

这是典型的差一错误(并且您正在调用 UB)。

关于C++ 数据变化无明显原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11039138/

相关文章:

c++ - 断言代码不编译

c++ - 错误 : expected primary-expression before ‘=’ token when using for loops

c++ - 使用 C++/CLI 包装 native C++ 模板化类

c++ - 为什么 CMake 找不到 GTest(Google 测试)?

c++ - 在递归函数中使用内联原型(prototype) C++

c++ - 具有可变数量的模板参数的简单方法

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c++ - vector push_back 与转发?

c++ - boost python 问题

c++ - 如何使用c函数计算文本文件中的单词数