控制台在输出指针数组和C++迭代时崩溃
Console crashes outputting pointer array and iterations C++
我正忙于研究一个简单的概念,以在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
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 迭代时从向量和内存中删除对象
- 如何在c++迭代器类型中包装std::chrono
- 带过滤器的现代迭代c++集合
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- C++矢量迭代
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 擦除while循环中迭代的元素
- 实现一个在集合上迭代的模板函数
- 对于set上的循环-获取next元素迭代器
- 在向量内的向量上迭代
- 为什么output_editor Concept不需要output_e迭代器标记
- TSP递归解的迭代形式
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器