Question on dynamic memory allocation

Dear all:

I ran a sample code from this website:
http://www.cplusplus.com/doc/tutorial/dynamic/

The code demonstrates how to dynamically allocate memories and it runs correctly.

Now I slightly change the above code, without using dynamic allocation technique.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

using namespace std;

int main(void)
{
    size_t number;

    cout << "How many numbers would you like to type? ";
    cin >> number;

    int arr[number];

    for (size_t n = 0; n != number; ++n) {
        cout << "Enter number: ";
        cin >> arr[n];
    }

    cout << "You have entered: ";
    for (size_t n = 0; n != number; ++n)
      cout << arr[n] << " ";

    cout << endl;
    return 0;
}


I suppose that line 12 will generate an error since for static allocation, only "fixed"-size array can be defined. However, the above code runs just as correctly as using new and delete.

I am just wondering why this would happen?

I am using Code::Blocks 12.11 on Ubuntu.

Thanks.
GCC has an extension allowing variable sized runtime arrays, which technically aren't legal until C++14 is released. If you want to generate an error from this, as you should, when compiling specify -Wall -Wextra -pedantic-errors in your command line for building (In the build options if you are using code::blocks).
NT3, thanks for your explanation.

So basically you mean that the code should generate an error. It runs only because I am using Code::Blocks with GCC as the compiler?
Yes - it only works because you're not using C++14 and your compiler supports it as a language extension.
Topic archived. No new replies allowed.