Create an array when the size is a variable not a constant

There is no proper way to do this, as a program with any variable length array is ill-formed.

An alternative, so to speak, to a variable length array is a std::vector:

std::vector<char> Sbuf;

Sbuf.push_back(someChar);

Of course, I should mention that if you are using char specifically, std::string might work well for you. Here are some examples of how to use std::string, if you’re interested.

The other alternative to a variable length array is the new operator/keyword, although std::vector is usually better if you can make use of it:

char* Sbuf = new char[siz];

delete [] Sbuf;

However, this solution does risk memory leaks. Thus, std::vector is preferred.

Leave a Comment