Home > Software engineering >  Built-in array with variable size?
Built-in array with variable size?

Time:02-21

Chapter 2.3.2 of The C Programming Language lists this constructor:

class Vector {
public:
    Vector(int s) :elem{new double[s]}, sz{s} { }
private:
    double* elem;
    int sz;
};

As far as I know, the array size must be a constant expression, and s isn't. Is this legal? If so, why?

CodePudding user response:

Yes, it's legal because the array is allocated at runtime with the 'new' operator.

If you want to allocate an array at compile-time, you must provide a const int, or constant expression.

int count = 0;
cin >> count; 
int* a = new int[count];  // This is dynamic allocation happen at runtime.
int b[6];                 // This is static allocation and it happen at compile-time.
  •  Tags:  
  • c
  • Related