static vs dynamic array(new operator)

My professor says that "we are not planning to use a dynamic array", and he wrote that "fixed size array is more useful". However, I don't understand why he used a new operator in his code.

For example, he wanted to give the user the option to choose the size of the array from the test drive(main), so he created a copy constructor that gets the new size and copies it into the array size, and then he uses a new operator.

1
2
3
4
5
6
stack::stack(int n){
  top = 0;
  arrSize = n; 
  arr = new int[arrSize];    // Why ???
}

You see, he says we are not planning to use a dynamic array, then why did he use a new operator? Why not something like this:

1
2
3
4
5
6
stack::stack(int n){
  top = 0;
  arrSize = n;
  arr[arrSize];     // why not?
}




Last thing is, he was writing a program working with arrays to show the difference between shallow copy vs deep copy in C++. As we know deep copy uses dynamic memory, so do you think that might be the reason he is using a new operator ?
Last edited on
why not...
it isn't legal. that type of array, the size must be known when you write the code, it can't be a variable. A few compilers support doing that, but its not legit.

new means dynamic memory is used.
but a dynamic array is one that can change size on the fly.

There is a subtle difference there. An array made of dynamic memory can be resized with some effort, its expensive and best avoided or done rarely. If you did it every time you added 1 item and you added a lot of items, you would notice slow behavior.

he uses new because he wants the size of the array at run-time, not compile time, see the "isn't legal" comment above. Its as simple as that.



Utility is a matter of debate, but in terms of code maintenance, use a std::vector. A vector is, at core, just a dynamically-allocated array (just like your professor is doing), except it provides the following advantages:

  - RAII: you don't have to mess with new[] and delete[]
  - you won't make a mistake
  - you can resize easily if needed
  - you don't have magic bad stuff happen to you, like automatic downcasting to a pointer
  - you can query its size and other attributes
  - you can treat it like a fundamental type

You can argue that an array is faster, but only with skewed use-cases that essentially cheat by targeting vector construction and forced deep copy.
I suspect the prof. won't allow it yet. A vector can also be a stack with push and pop commands available.


- you won't make a mistake
I disagree. It just prevents certain common mistakes. You can for sure use [] with a bad value that causes... a pointer access violation... just like arrays.

arrays are going to be insignificantly faster, a few clock cycles here and there. Why includes: it updates and maintains size, which arrays do not. If you use at() to avoid the above [] issues, that has overhead also.


Topic archived. No new replies allowed.