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!
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++.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With