c++ - 控制台崩溃输出指针数组和迭代 C++

标签 c++ arrays pointers

我正忙于研究一个简单的概念,以在 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/

相关文章:

python - 让我们为python的numpy做一个N维像素分箱/分桶的引用实现

c - 指针指向的元素的索引

c - 从 main 传递数组并通过另一个函数修改它

c++ - Vulkan SDK 可再发行组件

Python通过包含列表的字典列表循环创建新字典的最佳方法

c++ - 为什么 lambda 中的变量捕获如此复杂?

python - 同时并行读取 numpy 数组

c++ - C++ 和混合编程中指针的默认参数

c++ - makefile 中提到的依赖项的修改是否未被 make 识别?

c++ - MSVC 2008 Express Edition 编译器做什么和不做什么