Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C String array's array

Tags:

arrays

c

pointers

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};
like image 473
user2433045 Avatar asked May 29 '13 15:05

user2433045


2 Answers

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
like image 79
zakinster Avatar answered Sep 20 '22 20:09

zakinster


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

like image 23
StoryTeller - Unslander Monica Avatar answered Sep 23 '22 20:09

StoryTeller - Unslander Monica