XPost: alt.comp.lang.c++.misc
On 29/10/2024 05:30, Student Project wrote:
Do you guys use dynamic arrays to create arrays at compile time (without using vector class)? For example:
"Dynamic compile-time" is an oxymoron.
What you are doing here is creating a C-style array at run-time.
There's nothing wrong with using C-style arrays when you need them, but
if you are creating the array in dynamic memory (with "new") and a size
known only at run time, then it's usually better to use a vector<> for flexibility and convenience unless you are trying to keep overheads to
the absolute minimum.
And if you know the size of the array at compile time, consider using a std::array<> type instead of a C-style array. It is again more flexible
and somewhat "safer", but has no overheads.
No matter what kind of array you have, however, remember that in C++,
arrays of size N are indexed from 0 to N-1. Loops are therefore almost invariably of the form "for (size_t i = 0; i < size; i++) ...". Your
code has an off-by-one error.
Note that if you had used a std::array<> and have good warnings enabled
in your compiler, there's a fair chance that the compiler would have
spotted that error. And if you had used a std::vector<> appropriately,
you could have got a run-time exception showing the problem. And if you
had used either of these, you could have used a modern C++ syntax for
the loop that doesn't need the endpoints spelt out in the code - when
you don't write these things manually, it's a lot harder to make a mistake.
Keep up the learning!
--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)