-2

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.
  • 2
    @Vlad's answer explains the issue/solution, and the dupe I linked explains why you're getting different behavior in different environments. – Stephen Newell Sep 12 '22 at 16:37
  • Welcome to Stack Overflow. "when i try to get the data of a slot in an dynamic array, i get an exception" In your own words, *what part of this code do you think creates a dynamic array*? (Can you think of a reason why that line of code might not be doing what you expect? Hint: would the code `int example(10);` create a *static* sized array? Why or why not? How about the code `int example[10];`?) – Karl Knechtel Sep 12 '22 at 16:39
  • ***it runs perfectly. what is happening and what should i do to fix this?*** Unfortunately sometimes broken code appears to work. This is the worst behavior of undefined behavior. – drescherjm Sep 12 '22 at 16:39

1 Answers1

3

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;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335