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

Console crashes outputting pointer array and iterations C++

本文关键字:C++ 迭代 崩溃 数组 输出 指针 控制台      更新时间:2023-10-16

我正忙于研究一个简单的概念,以在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会容易得多。(

int * pArray;
int SIZE;
int module;
pArray = new int[SIZE];

SIZE还没有初始化,所以,它可能是一些垃圾值。在使用前进行初始化。

你也可以检查新的成功/失败。

pArray = new(nothrow) int[SIZE];
if(pArray)
//logic