C99 as well as (according the current drafts) C++14 provide dynamic arrays, i.e. arrays of automatic storage, but run-time determined size.
Since the Standard does not mention the stack (at least not in the sense of a predetermined location in memory), there is no guarantee that dynamic arrays are allocated on the stack, but the general understanding is that they are.
The implementation provided by GCC, for example, guarantees it: http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
Here is how you can use dynamic automatic arrays to allocate a buffer of char
according to your specifications:
#include <iostream>
#include <algorithm>
void foo(int alloc) {
/* Allocate data on the stack, the size of `alloc`. */
char c[alloc];
/* Do something with the buffer. I fill it with 'a's. */
std::fill(c,c+alloc,'a');
/* And print it. */
for (int i = 0; i < alloc; ++i)
std::cout << c[i];
std::cout << std::endl;
}
int main()
{
int alloc;
std::cin >> alloc;
foo(alloc);
return 0;
}
(Clearly, if you want to use this buffer to store objects larger than char
, you might need to make sure of alignment, i.e. you might have to move a few bytes inside the buffer to get a properly aligned address.)
C++14 is also likely to provide a C++-style container for dynamic automatic arrays, std::dynarray
. The idea is that they should be allocated on the stack, too, if possible (cf. Why both runtime-sized arrays and std::dynarray in C++14?).