p_array++ 之后的“Project.exe 已触发断点”;在 Visual Studio 2015 中
Posted
技术标签:
【中文标题】p_array++ 之后的“Project.exe 已触发断点”;在 Visual Studio 2015 中【英文标题】:"Project.exe has triggered a breakpoint" after p_array++; in Visual Studio 2015 【发布时间】:2016-10-31 20:18:21 【问题描述】:所以我再次尝试学习指针,当我输入一个数字时,Visual Studio 给了我一个错误。 这是来源:
// Includes
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
// Variables
int amount;
// Main function
int main()
cout << "How many numbers should be in this array: ";
cin >> amount;
int *p_array;
p_array = new int[amount];
for (int i = 0; i < amount; i++)
cout << (int)p_array << endl;
p_array++;
delete[] p_array;
_getch();
return 0;
我知道p_array++;
有问题。
当我尝试在 Code::Blocks 中编译它时,它运行良好(在代码块中编译时,我删除了 #include "stadfx.h"
并将 _getch();
更改为 getch();
)。
附:我是 C++ 新手:P
【问题讨论】:
问题出在delete[] p_array;
这个bug的原因是p_array
不再指向使用new分配的地址,因为你在循环中增加了它。
@drescherjm 谢谢!我用你的小费修好了。
【参考方案1】:
我通过这样做修复了它:
// Includes
#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
// Variables
int amount;
int *pointer;
// Main function
int main()
cout << "How many numbers should be in this array: ";
cin >> amount;
int *p_array;
p_array = new int[amount];
pointer = p_array;
for (int i = 0; i < amount; i++)
cout << (int)p_array << endl;
p_array++;
p_array = pointer;
delete[] p_array;
_getch();
return 0;
我创建了一个名为pointer
的指针并存储了p_array
的原始地址,然后在delete[] p_array;
之前我将存储在pointer
中的地址分配给了p_array
。
感谢 drescherjm 告诉我问题出在哪里。
我想没有人需要这个解释,但我想把它写在这里。
【讨论】:
我忘了补充,谁能告诉我我的问题有什么问题?我之所以问,是因为它收到了 3 次反对票,但我不知道出了什么问题。以上是关于p_array++ 之后的“Project.exe 已触发断点”;在 Visual Studio 2015 中的主要内容,如果未能解决你的问题,请参考以下文章