gpt4 book ai didi

带地址的 C++ 数组迭代 - 堆损坏

转载 作者:太空狗 更新时间:2023-10-29 23:50:33 25 4
gpt4 key购买 nike

我是 C++ 的新手,正在尝试一些东西。所以最近我尝试在堆上创建一个 int 数组并使用寻址而不是使用 [x] 的标准方法对其进行迭代。

每次我执行我的代码时,我都会收到堆损坏错误。我尝试了几件事(也在此处搜索了 stackoverflow)但找不到任何答案。

int* p = new int[5];

for (int i = 0; i <= 4; i++){
/*p[i] = i;
cout << p[i] << endl;*/ //This is the standard way and works

*p = i;
cout << *p << endl;

p = (p + sizeof(*p)); //iterate the pointer through the heap addresses
}

delete[] p;

应用程序运行并向我显示填充的数组值 {0,1,2,3,4} 但随后崩溃。

我收到以下错误消息:

检测到堆损坏:在 0x00C31B68 处的 CRT block (#225) 之后。CRT 检测到应用程序在堆缓冲区结束后写入内存...

提前致谢

最佳答案

当你这样做的时候

p = (p + sizeof(*p));

您正在对数组执行 sizeof(int) 整数步,超出了数组的范围。

您需要采取单个步骤:

p = (p + 1);

++p;

但请注意,这样做之后,p 不再指向任何可以调用 delete[] 的地方。您需要保留指向原始地址的指针:

int* arr = new int[5];
int* p = arr;

....

delete[] arr;

但是您没有理由首先使用 new 分配数组。

int arr[5];
int * p = arr;
....

关于带地址的 C++ 数组迭代 - 堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29163713/

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