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);