user1298272 user1298272 - 1 month ago 9
C Question

Rerefence to a const char* array

I am trying to avoid to repeat my code for 5 differentes arrays. I have 3 arrays (could be more in future):

const char *FirstlistOfOptionText[2] = {OPT_1,
OPT_2};
const char *SecondlistOfOptionText[2] = {OPT_1,
OPT_2};
const char *ThirdlistOfOptionText[2] = {OPT_1,
OPT_2};


THe elements in each one will not be the same. Now they are because I just copy&paste them. Number of elements won't neither.

I have a function in which I want to print every element of a list depending on a value I give as parameter. Also, I need to print one of those elements in other color (all in white except one in green).

I just want to have one code for printing and selecting the color as I have right now. But I want to select the correct array before doing that. I thought about:

const char *listOfOptions[];
if(menu_t.first_level_option == 0) {
listOfOptions = FirstlistOfOptionText;
}
if(menu_t.first_level_option == 1) {
listOfOptions = SecondlistOfOptionText;
}
if(menu_t.first_level_option == 2) {
listOfOptions = ThirdlistOfOptionText;
}


But I get some errors about storage size of 'listOfOptions' isn't known. Or that I can't use const char** for a char* or thing like that.

What is the correct way to do this?

Answer

Essentially you neeed to make listOfOptions a char **;

An array of pointers can be referenced through a pointer to pointers (that's what the char ** is).

The size will be unknown to anyone using listOfOptions thus you need a way to determine the size. Either terminate the list with a NULL pointer or you will have to use a 2nd variable (listOfOptionsSize) that tracks the size.

So the code below should compile (I opted for the NULL terminated lists).

const char *FirstlistOfOptionText[]   = {"a",  "b", NULL};
const char *SecondlistOfOptionText[]   = {"c", "d", "e", "f", NULL};
const char *ThirdlistOfOptionText[]  = {"e",  "f", "g", NULL};    

const char **listOfOptions= NULL;  // pointer to pointer(s)
int first_level_option= 2;         // some value for testing


if(first_level_option == 0) {
    listOfOptions = FirstlistOfOptionText;
}
if(first_level_option == 1) {
    listOfOptions = SecondlistOfOptionText;
}
if (first_level_option == 2) {
    listOfOptions = ThirdlistOfOptionText;
}

printem(listOfOptions);

Now for your printing function, it will get the pointer to the list of pointers as a parameter and and will look like this:

void printem(const char **listOfOptions)
{
     const char *word;

     while (*listOfOptions!=NULL) {  // while the pointer in the list not NULL
        word= *listOfOptions;        // get the char * to which listOfOptions is pointing
        printf("entry: %s\n", word);
        listOfOptions++;
     }
}

Oh, and welcome to C-Pointer Hell :-)

Comments