Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a Char*[]

Question is in the title, how do I initialize a char*[] and give values to it in C++, thank you.

like image 580
DogDog Avatar asked Feb 10 '10 20:02

DogDog


People also ask

How do you initialize a char?

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.

How do you initialize a char array?

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)

How do you initialize a char string?

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' };

How do you initialize a character pointer?

ab = malloc(sizeof(char) * (NUM_CHARS + 1)); Then your sprintf will work so long as you've made enough space using malloc .


2 Answers

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; 
like image 88
Stephen Cross Avatar answered Sep 18 '22 21:09

Stephen Cross


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.

like image 41
John Weldon Avatar answered Sep 21 '22 21:09

John Weldon