c - Create an array of strings without allocating each string -


i trying figure out how create array of strings (considering know max length of each string).

char** strings = null; strings = malloc (5*sizeof(char*)); 

once did that, how can fill array without need allocate each string separately? lets know max length of string 20, how set it?

after allocation of string wish following:

strings[0] = "string"; strings[1] = "another string"; 

etc.

thanks

you can declare array of pointers char , assign string literals pointers

char *strings[5];   strings[0] = "string"; strings[1] = "another string";  /* ... */  

but note that, these strings immutable.

you can use array of char arrays

char strings[5][20];    // know max length of string 20 strcpy(strings[0], "string"); strcpy(strings[1], "another string"); /* ... */ 

one of advantage of latter strings mutable.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -