Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I allocate `std::array` on stack without knowing size at compile time?

Tags:

c++

When allocating on the stack, I don't necessarily need to know the size of a C array being allocated at compile time. i.e. I can do this:

void foo(size_t s) {
    uint8_t bar[s]; // `s` not known at compile time
    some_func_that_uses_bar(bar, sizeof(bar));
}

However, to be less error-prone, it feels I should be able to do this with C++ std::arrays as well, yet I haven't been able to figure out how (nor whether it's even possible).

like image 247
Peter Jankuliak Avatar asked Jan 30 '26 06:01

Peter Jankuliak


1 Answers

No, you can't. C has added special support for variable-length arrays, but C++ has not. You can get a similar effect using alloca(), but that's not a standard function and will require additional work if you're using it with a class requiring a specific alignment, and requires you to manually invoke the constructors and destructors.

For that use case, a normal C++ programmer would use std::vector.

like image 197
Sneftel Avatar answered Feb 01 '26 22:02

Sneftel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!