I was doing my c++ assignment with microsoft visual studio and i noticed something unusual

Viewed 61

when i try to get the data of a slot in an dynamic array, i get an exception. but if i run the same code using a different compiler such as the online one(https://www.onlinegdb.com/online_c++_compiler), it runs perfectly. what is happening and what should i do to fix this? for reference, heres the code i ran on my visual studio

#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;
}

and heres the exception that was thrown when i run the code

Exception thrown at 0x00007FFC71355FDF (ntdll.dll) in cplusplus.exe: 0xC0000005: Access violation reading location 0x000002CE00000012.
1 Answers

In this record

int* arr = new int(n);

you allocated one object of the type int and initialized it by the value n.

In fact the above record is equivalent to

int* arr = new int;
*arr = n;

You need to allocate an array of n elements like

int* arr = new int[n];

And before exiting the program you should delete the allocated array

delete [] arr;
Related