0

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?

1
  • 1
    Don't put the ampersand in front of fruits and colors. Since they are arrays, they will be interpreted as pointers to their first elements in that situation. Commented Jan 31, 2014 at 23:27

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

8 Comments

const preservation FTW!
Is it possible for me to have preset_configurations be a char * const*? I am trying to pass it to the linux execv function which requires char * const*.
Just remove the first const from all of them. Although, technically, you should have char const since you're pointing to string constants.
@ooga note, that will flag at least a compiler warning for deprecation since the literal is const by nature. Most C-compilers will allow it regardless unless some pretty pedantic warnings are being used. Ex: clang will report: "Initializing 'char *const *' with an expression of type 'const char *const [3]' discards qualifiers in nested pointer types."
@unexpected62 ensconced within this answer to a somewhat related question is a diatribe on every conceivable meaning of const and * through double-indirection (i.e. pointers to pointers). It may help you understand better.
|
0
typedef const char const *(*cp3)[3];
cp3 preset_configurations[3] = {
    NULL,
    &fruits,
    &colors,
};
//printf("%s\n", (*preset_configurations[1])[2]);//orange

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.