0

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 !

Vlad
  • 63
  • 1
  • 5

1 Answers1

2

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]=' '}, ""}
};
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • You're right on my (briefly written) example mistake. But, solution of allocating char y[100]; is not desired. I'm looking for specific reasons to align the solution as for 1D example. – Vlad Sep 06 '14 at 17:44
  • 1
    No such solution is possible, because multi-dimensional arrays in C are never sparse nor jagged, meaning each dimension must have the same fixed length. You can either set a fixed length as I have, or you can go back to using `char*` for the second column and allocate storage for it outside. Either use `malloc()` or some stack-allocated pool of strings, and set the pointers in the second column of your matrix to point to those dynamically-sized arrays outside. – John Zwinck Sep 07 '14 at 01:07