Search code examples
c++arraysdynamic-allocation

Creating a user-inputted sized Array using new operator


I have a few array-related questions. I've studied that array-size must be constant on declaration/compiler must know its value. But using the GNU GCC compiler (C++11 standard filter) and I am able to perfectly compile and run a program using a variable as array size, when declaring said array dynamically (using new)

int num;
cout << "How big an array? ";
cin >> num;
int *arr = new int [num];

Ques1) Is this considered standard? My profs are contradictory.

Ques2) If it is standard, in that case, is it possible to extend the size of the array (or any array) after creation?

Ques3) Again, if this expression is standard, then is it possible to use it within a function - eg. using a function to create such an array? (if so, how?)

(PS: Hi, I'm new here and also still a novice in C++)


Solution

  • Ques1) Is this considered standard? My profs are contradictory.

    Yes, this is completely valid. Note that you need to explicitly delete the memory pointed by arr using operator delete[]. It is much better to use a std::vector<int> which will perform the memory management for you.

    You might be mistaken with variable length arrays(VLAs), which are not allowed in C++:

    // same num as the one in your example
    int arr[num]; // ERROR
    

    This is valid in C but invalid in C++(C++14 will include VLAs, although they will have some differences with C VLAs).

    Ques2) If it is standard, in that case, is it possible to extend the size of the array (or any array) after creation?

    No, you can't extend it. You can allocate a bigger array, copy the elements and delete the previous one. Again, this is done automatically if you're using std::vector<int>.

    Ques3) Again, if this expression is standard, then is it possible to use it within a function - eg. using a function to create such an array? (if so, how?)

    Yes, of course:

    int *allocate(size_t size) {
        return new int[size];
    }
    

    But again use std::vector:

    int num;
    cout << "How big an array? ";
    cin >> num;
    std::vector<int> arr(num); // num elements, all of them initialized to 0
    // insert 42 at the end. reallocations(if any) are done automatically
    arr.push_back(42);