Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an array whose size is initially unknown?

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!

like image 503
moonbeamer2234 Avatar asked Mar 16 '14 03:03

moonbeamer2234


People also ask

How do you initialize an array of unknown size?

const char* pArray = new char[x]; It should be noted that the second option is wasteful. Because you can not dynamically resize this array you must allocate a large enough chunk to hold the maximum number of items your program could create. Finally, you can always use data structures provide by C++.

How do you initialize an array of a certain size?

To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.


1 Answers

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);
like image 72
herohuyongtao Avatar answered Sep 19 '22 21:09

herohuyongtao