C array of string arrays

I am going to store arrays of strings in an array in C.

for instance

{ {"hello", "world"}, {"my", "name", "is"}, {"i'm", "beginner", "point", "makes"} } 

I would like to save the above data.

I tried to use

 char *arr1 = {"hello", "world"}; char *arr2 = {"my", "name", "is"}; char *arr3 = {"i'm", "beginner", "point", "makes"} 

But I do not know how to store these arrays in one array.

Thanks in advance.

ps.

How to print the whole item using?

 const char **arr[] = {arr1, arr2, arr3}; 
+6
source share
2 answers

If you need a char** array, just do:

 const char *arr1[] = {"hello", "world", NULL}; const char *arr2[] = {"my", "name", "is", NULL}; const char *arr3[] = {"i'm", "beginner", "point", "makes", NULL}; const char **arr[] = {arr1, arr2, arr3, NULL}; 

Note that the NULL terminators here are designed to track the sizes of different arrays, as in the NULL-terminated string.

 int i, j; for(i = 0; arr[i] != NULL; ++i) { for(j = 0; arr[i][j] != NULL; ++j) { printf("%s ", arr[i][j]); } printf("\n"); } 

What will be output:

 hello world my name is i'm beginner point makes 
+10
source

Unlike my initial assessment, this can be done using a single literal.

 #include <stdio.h> int main() { char* arr[3][4] = { {"hello", "world"}, {"my", "name", "is"}, {"i'm", "beginner", "point", "makes"} }; printf ("%s", arr[2][3]); return 0; } 

Arrays 1 and 2 will be padded with zeros at the end of length 4.

output:

brands

Tested here: http://ideone.com/yDbUuz

+8
source

Source: https://habr.com/ru/post/946097/


All Articles