How to initialize an array whose size is initially unknown?

moonbeamer2234 picture moonbeamer2234 · Mar 16, 2014 · Viewed 79.2k times · Source

Say I have this:

int x;
int x = (State Determined By Program);
const char * pArray[(const int)x]; // ??

How would I initialize pArray before using it? Because the initial size of the Array is determined by user input

Thanks!

Answer

herohuyongtao picture herohuyongtao · Mar 16, 2014

Size of dynamically created array on the stack must be known at compile time.

You can either use new:

const char* pArray = new char[x];
...
delete[] pArray;

or better to use std::vector instead (no need to do memory management manually):

vector<char> pArray;
...
pArray.resize(x);