gpt4 book ai didi

c++ - 为什么调试器只显示我的数组指针中的一个元素?

转载 作者:太空狗 更新时间:2023-10-29 23:31:05 26 4
gpt4 key购买 nike

首先:我知道 new 是执行此操作的 C++ 方法。我只是想证明重现此错误的方法不止一种,而且两种方法都令人难以置信。

我有这个源文件的两种形式。我正在尝试调试另一个编程任务,但我并没有就此寻求帮助。基本上,我正在尝试将 set 重新实现为一个类,其中包含大小字段和指向 int 数组的指针。下面是使用 new 的代码:

测试新.cpp

int main()
{
int size = 1;
int *elements = new int[size];
elements[0] = 0;
size++;
int * temp = new int[size];
for (int i = 0; i < (size - 1); i++)
{
temp[i] = elements[i];
}
delete[] elements;
temp[size] = size;
elements = temp;
elements[1] = 1;
delete[] elements;
}

再次,使用不太受欢迎的 alloc 函数:

测试分配.cpp

int main()
{
int size = 1;
int * elements = (int *) malloc(sizeof(int) * size);
elements[0] = 0;
size++;
elements =(int *) realloc(elements,size * sizeof(int));
elements[1] = 1;
free(elements);
}

在这两种情况下,我的目标都是创建一个数组,然后附加到它。然而,在这两种情况下,在 Visual Studio 2010 中构建并运行它之后,数组根本没有增长,只有 1 个“槽”可以让我的项目进入。在 VS 的调试器中,我监视 elements 数组指针;附件是截图。两个版本的代码都是一样的。

My watches at the end of the program

-- 断点在 delete[]/free() 调用处。

说真的,我做错了什么?这一定是一个逻辑错误,我梳理了四分之一的 malloc/reallocnew 示例,并阅读和重读我的教科书,我看不出有什么问题!

我觉得我应该有一行将分配的内存拆分成一个数组,但是 new int[] 调用不是这样做的吗?

最佳答案

除了代码的任何其他问题,你必须要么做JoeG提及并拥有多个 watch ,或者像这样设置一个 watch :

elements,5

将导致:

enter image description here

我不知道是否有 VS2010 的更新列表,但这仍然有效: Symbols for Watch Variables
和: View array in Visual Studio debugger?

关于c++ - 为什么调试器只显示我的数组指针中的一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9671591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com