I am going to store string arrays in an array in C.
For example
{
{"hello", "world"},
{"my", "name", "is"},
{"i'm", "beginner", "point", "makes"}
}
I'd like to store above data.
I tried to use
char *arr1 = {"hello", "world"};
char *arr2 = {"my", "name", "is"};
char *arr3 = {"i'm", "beginner", "point", "makes"}
But I don't know how to store those arrays in one array.
Thanks in advance.
ps.
How to print all element with?
const char **arr[] = {arr1, arr2, arr3};
If you want 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 are here to keep track of the different arrays' sizes, just like in a 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");
}
Which would outputs :
hello world
my name is
i'm beginner point makes
Unlike my initial assessment, it can be done with 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 by zeroes at the end to be of length 4.
output:
makes
Tested it here: http://ideone.com/yDbUuz
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