|
发表于 2020-11-8 10:39:14
|
显示全部楼层
https://stackoverflow.com/questi ... have-constant-value
C++ doesn't allow variable length arrays. The size must be a constant. C99 does support it so if you need you can use a C99 compliant compiler. Some compilers like GCC and Clang also support VLA as an extension in C++ mode
But if C++ is a must then you can use alloca (or _alloca on Windows) to allocate memory on stack and mimic the C99 variable length array behavior
Amta = (int *)alloca(sizeof(int) * size);
This way you don't need to free the memory after going out of scope because the stackframe will automatically be restored. However you need to be very careful while using this. It's still better to use std::vector in C++ for these purposes |
|