我正忙于研究一个简单的概念,以在 C++ 中显示指针数组和 for 循环的迭代
我的编译器没有给出太多信息,当我运行该程序时,控制台显示以下内容并返回 3“应用程序已请求运行时以异常方式终止。
崩溃发生在这一行:
cout << i + 1 << " " << *(pArray + i) << endl;
但是当我运行这个程序时忽略 i + 1 或 *(pArray + i) 它运行没有错误或崩溃。
像我上面那样尝试输出是否违法?
代码见下:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int * pArray;
int SIZE;
int module;
pArray = new int[SIZE];
cout <<"Enter the number of Assignments ";
cin >> SIZE;
cout <<"input assignment number " ;
for (int i = 0; i < SIZE; i++)
{
cin >> module;
*(pArray + i) = module;
}
// Print array
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << " " << *(pArray + i) << endl;
}
cout << endl;
delete[] pArray; // Deallocate array via delete[] operator
return 0;
}
诚然,问这个问题我有点紧张,但我只需要有人解释为什么会发生这种情况,因为我正在努力寻找有关此类情况的任何引用资料。
谢谢
最佳答案
在初始化之前使用 SIZE
两行。
移动
pArray = new int[SIZE];
在您获得 SIZE
的值之后。
(另外:使用 std::vector
会容易得多。)
关于c++ - 控制台崩溃输出指针数组和迭代 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33054051/