【问题标题】:Access violation when "resizing" array in C++在 C++ 中“调整大小”数组时访问冲突
【发布时间】:2015-03-24 13:44:33
【问题描述】:

所以我正在尝试创建一个函数,将成员数组“调整大小”为作为参数传递的新大小。通过“调整大小”,我的意思是它应该将成员数组设置为具有新大小的新数组,复制旧数组中的元素,然后释放与旧数组关联的内存。这是我目前所拥有的:

void MemoryTest::resize(unsigned int new_size) {
    if (size == new_size)
        return;

    int* oldPtr = elements;

    elements = new int[new_size + 1];
    for (int i = 0; i < (new_size < size) ? new_size : size; i++)
        elements[i] = oldPtr[i];

    elements[new_size] = '\0';

    if (size > new_size)
        size = new_size;

    delete[] oldPtr; // Deallocate old elements array
}

elements 是一个私有成员 int*,初始化为 NULL。

但是,当它开始 for 循环时,程序会挂起一段时间,然后对 elements[i] = oldPtr[i] 行给出访问冲突。如果我错了(我可能是),请有人纠正我,但我的理解是 oldPtr 应该是指向与元素相同的初始点的指针。然后,我将元素设置为等于一个新数组,因此两者现在指向两个不同的东西。然后我遍历元素,将每个项目设置为等于旧数组中的对应项。

另外,虽然我通常会使用向量来避免这种情况,但我正在尝试更加熟悉 C++ 中的指针和内存分配。

提前致谢!

【问题讨论】:

  • 第一次调用此函数后,您的成员变量size 不准确。我无法确定它是否准确之前
  • 现在您已经更改了代码,当数组变大时,您的成员变量size 将会出错。
  • 我试图让 size 反映元素的数量,而不是数组中的内存点数量,所以它应该只在添加新元素时增加。话虽如此,问题确实在于大小,这导致了迭代 for 循环时出现问题。
  • @user2884505 - I'm trying to make size reflect the number of elements, not the number of memory spots in the array, 这就是为什么 vector 同时拥有 sizecapacity 成员。
  • 我猜是另一个只使用向量的原因哈哈。感谢您的澄清!

标签: c++ arrays pointers access-violation


【解决方案1】:

for (int i = 0; i &lt; (new_size &lt; size) ? new_size : size; i++)

应该阅读

for (int i = 0; (i &lt; (new_size &lt; size)) ? new_size : size; i++)

所以,for (int i = 0; i &lt; ((new_size &lt; size) ? new_size : size); i++) 应该更正您的代码。

【讨论】:

  • 为什么不只是一个简单的for (int i = 0; i &lt; size; ++i)
  • @PaulMcKenzie 对于新数组来说可能迭代次数过多。
  • @DrewDormann - 当然,我假设 size 在所有动态内存恶作剧完成之前保持不变,并且在函数结束时,size 设置正确到新尺寸。
  • 谢谢你,成功了!我必须等待两分钟才能接受这个答案,但这是我经历过的最短的等待时间之一,哈哈。真的很感谢大家!
猜你喜欢
  • 2018-11-16
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多