Array of strings literal declaration ...cant make it work

Hello all,

I am trying to make a menu system with a rotary encoder for a flight sim. As part of that I just want to declare each menu name and its menu items. I suspect C can do this even if I can't :slight_smile:

My first attempt:


// declare a struct/object to hold the menu name and items
typedef struct
{
const char *name; // a basic string
__ const char *values; // an array of strings__
} Menu;


The idea is this would allow me to instantiate objects of type Menu and refer to things like

Serial.println( myMenu.name );
Serial.println( myMenu.values[1] );

but when I try to create a menu:

// now create an instance of a menu using literals
Menu editMenu =
{
"Edit",
** { "Cut", "Copy", "Paste" }**
};

I get this:
error: too many initializers for 'const char* [0]'

even this wont work:

typedef struct
{
const char *name;
const char *values;
} Menu;

Menu editMenu =
{
"Edit",
{} // leave it empty for now
};

void setup()
{
const char *v = { "Cut", "Copy", "Paste" };
editMenu.values = v; // late initialize menu values
}

gives
error: incompatible types in assignment of 'const char* [3]' to 'const char* [0]'
in the editMenu.values = assigment line

outside the struct I seem to be able to create these arrays of strings just fine:

char *simple = { "Cut", "Copy", "Paste" };

compiles no problem.

I am sure I am making a syntax mistake between **char, *char or even *(*char) ???
Could someone more knowledgable than me offer a clarification please ?

You need to specify a size for your array, otherwise its only a pointer. Its used for variable length structures and requires using dynamic memory (new,malloc).

Without dynamic memory you can do this:

struct Menu{
  const char *name;
  const char *values[3];
};

Menu editMenu = { "name", { "val1", "Val2", "val3" } };

Or, using a template, you can create structures of different sizes:

template< unsigned N >
  struct Menu{
    const char *name;
    const char *values[N];
};
Menu<3> editMenu = { "name", { "val1", "Val2", "val3" } };

editMenu.values = v; // late initialize menu values

This is not initialization, but an assignment. Assigning one array to another is illegal. You must use a loop to assign each value independently. How to copy an array

Very good, thank you !