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

Jaz*_*jef 3 c++ arrays iteration pointers heap-corruption

我是 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;
Run Code Online (Sandbox Code Playgroud)

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

我收到以下错误消息:

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

提前致谢

jua*_*nza 5

当你这样做时

p = (p + sizeof(*p));
Run Code Online (Sandbox Code Playgroud)

您正在sizeof(int)跨数组采取整数大小的步骤,超出其范围。

您需要采取单一步骤:

p = (p + 1);
Run Code Online (Sandbox Code Playgroud)

或者

++p;
Run Code Online (Sandbox Code Playgroud)

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

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

....

delete[] arr;
Run Code Online (Sandbox Code Playgroud)

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

int arr[5];
int * p = arr;
....
Run Code Online (Sandbox Code Playgroud)