当我尝试获取动态数组中插槽的数据时,出现异常。但是如果我使用不同的编译器(例如在线编译器)运行相同的代码(https://www.onlinegdb.com/online_c++_compiler https://www.onlinegdb.com/online_c++_compiler),它运行完美。发生了什么事以及我应该做什么来解决这个问题?作为参考,这是我在视觉工作室上运行的代码
#include<iostream>
using namespace std;
int main() {
int x, n;
cout << "Enter the number of items:" << "\n";
cin >> n;
int* arr = new int(n);
cout << "Enter " << n << " items" << endl;
for (x = 0; x < n; x++) {
cin >> arr[x];
}
cout << "You entered: ";
for (x = 0; x < n; x++) {
cout << arr[x] << " ";
}
return 0;
}
这是我运行代码时引发的异常
Exception thrown at 0x00007FFC71355FDF (ntdll.dll) in cplusplus.exe: 0xC0000005: Access violation reading location 0x000002CE00000012.
在此记录中
int* arr = new int(n);
您分配了一个 int 类型的对象并用值 n 对其进行了初始化。
实际上上面的记录相当于
int* arr = new int;
*arr = n;
您需要分配一个包含 n 个元素的数组,例如
int* arr = new int[n];
在退出程序之前,您应该删除分配的数组
delete [] arr;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)