boltup_im_coding
boltup_im_coding

Reputation: 6665

Make an array of arrays of strings

I have arrays of strings. I want to put these arrays into an array. How can I do so? I have tried this:

char const * const fruits[3] = {
    "apple",
    "banana",
    "orange",
};

char const * const colors[3] = {
    "red",
    "green",
    "blue",
};

char * preset_configurations[3] =
{
    NULL, /* leave the first one blank so that this list is 1-based */
    &fruits,
    &colors,
};

but I get warning: initialization from incompatible pointer type. Any idea?

Upvotes: 0

Views: 104

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40155

typedef const char const *(*cp3)[3];
cp3 preset_configurations[3] = {
    NULL,
    &fruits,
    &colors,
};
//printf("%s\n", (*preset_configurations[1])[2]);//orange

Upvotes: 0

ooga
ooga

Reputation: 15511

You need a double pointer and some consts (as well as getting rid of the ampersands) :

char const * const * preset_configurations[3] =
{
    NULL, /* leave the first one blank so that this list is 1-based */
    fruits,
    colors
};

EDIT: I suppose, given the extra information after I posted the above, that the best solution to your problem is:

// This will copy the characters of the words into the 3 16-byte arrays.
char fruits[3][16] = {
    "apple",
    "banana",
    "orange"
};
// Ditto.
char colors[3][16] = {
    "red",
    "green",
    "blue"
};
// This is how to point to the above.
char (*preset_configurations[3])[16] = {
    NULL, // this list is 1-based
    fruits,
    colors,
};

That way the strings are no longer constant strings (which, as you said, the exec functions don't want).

Upvotes: 3

Related Questions