user2433045
user2433045

Reputation: 63

C String array's array

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

Upvotes: 6

Views: 371

Answers (2)

zakinster
zakinster

Reputation: 10698

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

Upvotes: 10

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

Upvotes: 8

Related Questions