c 2d array static initialization with preserved size

539 Views Asked by At

similar to 1D array declaration :

char arr[]={[0 ... RESERVED_CHARS-1]=' ',[RESERVED_CHARS]='\0'};

please advice how / if possible to declare such 2D array ?

#define SAY_MAX_MSG_LEN 6
#define REP_MAX_MSG_LEN 8

char *var_msg_out[][3]={\
    {" Say ",[][0 ... SAY_MAX_MSG_LEN+1]=' ','\0'},\
    {" Reply ",[][0 ... REP_MAX_MGS_LEN+1]=' ','\0'}\
};
snprintf(var_msg_out[0][1],SAY_MAX_MSG_LEN,"hello");
printf("%s",var_msg_out[0]);

Thanks !

1

There are 1 best solutions below

2
On BEST ANSWER

The only part of what you have is this:

char *var_msg_out[][3]={
    {" Say ",[][0 ... SAY_MAX_MSG_LEN+1]=' ','\0'},
              ^ ???

There is a fundamental issue here: the element after " Say " is a char*, yet you are trying to assign to it as if it were a char array. The two are not the same thing: your char* can point to a literal string (like " Say ") with no problem, but you cannot initialize its characters because there is nothing to initialize--only a pointer!

You can fix it this way:

struct foo {
    const char* x;
    char y[100];
    const char* z;
};

struct foo var_msg_out[]={
    {" Say ", {[0 ... SAY_MAX_MSG_LEN+1]=' '}, ""},
    {" Reply ", {[0 ... REP_MAX_MSG_LEN+1]=' '}, ""}
};