'is it possible to define multidim arrays with #define directive in pure C?

I want to manage my packs of string constants separately from the computational code. I want to do it in separate file.

So, I need to create a multidim array of strings and conclude it under a STR_PACK_X.

If it is possible, can anyone route me right way with #define multidim-string-constants syntax?

Help me please, what's wrong with that attempt:

#define STR_PACK_X \
({ \
\ // comm1
    { "string1", "string2", "string3" }, \
\ // comm2
    { "string11", "string22", "string33" }, \
\ // comm3
    { "string111", "string222", "string333" } \
})

I want to use it like that:

int line_lim = 4, word_lim = 4, char_lim = 50;

if (flag1)
{ 
  char array[line_lim][word_lim][char_lim] = STR_PACK_1; 
  /* array processing */
  ... 
}
if (flag2)
{ 
  char array[line_lim][word_lim][char_lim] = STR_PACK_2; 
  /* array processing */ 
  ... 
}


Solution 1:[1]

As noted, you have several language violations here:

  • Parenthesis around an initializer list isn't valid, it gives the wrong syntax for what you wish to achieve.
  • You can't initialize a variable-length array.
  • You can't place characters after a \ line wrap, using // comments together with them is always problematic. I'd advise to indent all \ to a fixed source column.

It would seem that instead of an initializer list, you are rather looking to use a compound literal and then copy the contents from that one in run-time:

#include <stdio.h>
#include <string.h>

#define STR_PACK_X                                          \
(const char* [3][3])                                        \
{                                                           \
    { "string1",   "string2",   "string3"   }, /* comm1 */  \
    { "string11",  "string22",  "string33"  }, /* comm2 */  \
    { "string111", "string222", "string333" }, /* comm3 */  \
}

int main (void)
{
  int line_lim = 4, word_lim = 4, char_lim = 50;
  char array[line_lim][word_lim][char_lim]; // VLA, can't be initialized

  for(size_t i=0; i<3; i++)
  {
    for(size_t j=0; j<3; j++)
    {
      strcpy(array[i][j], STR_PACK_X[i][j]);
      puts(array[i][j]);
    }
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lundin