Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Does C++ have arrays whose length can be specified at run-time?

arrays LENGTH run-time
0
Posted

Does C++ have arrays whose length can be specified at run-time?

0

Yes, in the sense that STL has a vector template that provides this behavior. No, in the sense that built-in array types need to have their length specified at compile time. Yes, in the sense that even built-in array types can specify the first index bounds at run-time. E.g., comparing with the previous FAQ, if you only need the first array dimension to vary then you can just ask new for an array of arrays, rather than an array of pointers to arrays: const unsigned ncols = 100; // ncols = number of columns in the array class Fred { /*…*/ }; void manipulateArray(unsigned nrows) // nrows = number of rows in the array { Fred (*matrix)[ncols] = new Fred[nrows][ncols]; // … delete[] matrix; } You can’t do this if you need anything other than the first dimension of the array to change at run-time. But please, don’t use arrays unless you have to. Arrays are evil. Use some object of some class if you can. Use arrays only when you have to.

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123