Initialize an unknown size 2D array using macros in C

I worked on a small macro-projects that require me to give a 2-dimensional array in one of my macros myMacro({{0, 1, 2}, {2, 1, 0}}). Without the need to pass the size of the array to a macro, is there a way to expand it to the following: int[2][3] = { {0, 1, 2}, {2, 1, 0} }or something equivalent (any initialization that preserves the shape of the array will work)? Thanks in advance for any help

+4
source share
2 answers
#include <boost/preprocessor/tuple/size.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>
#include <boost/preprocessor/seq/for_each.hpp>

#define VA(...) __VA_ARGS__
#define TRANS(r, data, elem) { VA elem},

#define myMacro(name, arg)\
    int name[BOOST_PP_TUPLE_SIZE(arg)][BOOST_PP_TUPLE_SIZE(BOOST_PP_TUPLE_ELEM(0,arg))] = \
    { BOOST_PP_SEQ_FOR_EACH(TRANS, , BOOST_PP_VARIADIC_TO_SEQ arg)}

int main(){
    myMacro(a, ((1,2,3),(4,5,6)) );//=>int a[2][3] = { { 1,2,3}, { 4,5,6}, };
    return 0;
}
+4
source

If you have an upper limit for the second dimension, you can use sentinel values ​​such as:

#include <stdio.h>

#define MAXCOLUMNS 20
#define VALUE {{0,1,2,-1},{2,3,4,-1},{0,0,0,0,1,-1},{-1}}

int main()
{
  int v[][MAXCOLUMNS] = VALUE;
  int x, y;

  for (y = 0; v[y][0] != -1; y++)
    for (x = 0; v[y][x] != -1; x++)
      printf("[%d,%d] = %d\n", x, y, v[y][x]);

  return 0;
}

, . , ?

: @BLUEPIXYs , , C ( ).

+2

Source: https://habr.com/ru/post/1570028/


All Articles