A bit stupid doubt on C++ arrays - beginner

https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why

Basically you're running into undefined behavior. You are going outside the bounds of the array that you've created, but since arrays are basically the same as they were in C, there's no bounds checking. It appears to work "correctly", but if you kept adding to it, you'd probably run into a segmentation fault.

The problem is the way you've constructed your loop. You want x < n rather than <=.

I'd also suggest that it's poor practice to create your variables at the top of the function. Declare them as necessary.

int arraySize = 0;
cout << "Enter array size: ";
cin >> arraySize;
int arr[arraySize];

for(int i = 0; i < arraySize; i++)
{
    arr[i] = i;
    cout<< arr[i] << endl;
}
/r/learnprogramming Thread