Question is in the title, how do I initialize a char*[] and give values to it in C++, thank you.
In C++, when you initialize character arrays, a trailing '\0' (zero of type char) is appended to the string initializer. You cannot initialize a character array with more initializers than there are array elements. In ISO C, space for the trailing '\0' can be omitted in this type of information.
You can initialize a one-dimensional character array by specifying: A brace-enclosed comma-separated list of constants, each of which can be contained in a character. A string constant (braces surrounding the constant are optional)
A more convenient way to initialize a C string is to initialize it through character array: char char_array[] = "Look Here"; This is same as initializing it as follows: char char_array[] = { 'L', 'o', 'o', 'k', ' ', 'H', 'e', 'r', 'e', '\0' };
ab = malloc(sizeof(char) * (NUM_CHARS + 1)); Then your sprintf will work so long as you've made enough space using malloc .
Though you're probably aware, char*[] is an array of pointers to characters, and I would guess you want to store a number of strings. Initializing an array of such pointers is as simple as:
char ** array = new char *[SIZE];
...or if you're allocating memory on the stack:
char * array[SIZE];
You would then probably want to fill the array with a loop such as:
for(unsigned int i = 0; i < SIZE; i++){ // str is likely to be an array of characters array[i] = str; }
As noted in the comments for this answer, if you're allocating the array with new (dynamic allocation) remember to delete your array with:
delete[] array;
Depending on what you want to initialize to you could do any of:
char mystr[] = {'h','i',0}; char * myotherstring = "my other string"; char * mythirdstring = "goodbye"; char * myarr[] = {0}; char * myarr[] = {&mystr, myotherstring}; char * myarr[10]; char * myarr[10] = {0}; char * myarr[10] = {&mystr, myotherstring, mythirdstring, 0};
etc. etc.
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