Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing variable size arrays in C

Tags:

arrays

c

struct

I try to define a struct type with array members of variable size like this:

typedef struct {
  const int M;
  const int N;
  int       x[];    // Should be 1-D M elements
  int       y[][];  // 2-D M*N elements
} xy_t;

The reason for variable sized arrays is that I have a function that should work on variable dimensions.
However that gives an error, so I rewrote to:

typedef struct {
  const int M;
  const int N;
  int       *x;    // 1-D M elements
  int       **y;   // 2-D M* elements
} xy_t;

which compile fine. However, the problem is how to I initialize this?

static xy_t xy = {.M = 3, .N = 2, .x = ???, .y = ???};

.x = (int[3]){0} seems to work, but I haven't found a way to assign y.

I tried .y = (int[3][2]){{0,0}, {0,0}, {0,0}} and several similar variant without success.

like image 210
Einar Fredriksen Avatar asked Sep 14 '25 19:09

Einar Fredriksen


1 Answers

You can make member y a pointer to incomplete array type.

typedef struct {
  ...
  int       (*y)[]; // a pointer an array of unspecified length
} xy_t;

This would let initialize y with a compound literal.

xy_t xy;
xy.y = (int[3][2]){{0,0}, {0,0}, {0,0}};

However it will not be possible to dereference this 2D array because the type of xy.y is incomplete. This can be solved by assigning this pointer to a pointer to VLA with completed type.

int (*arr)[xy.N] = xy.y;

arr[i][j] = 42;
like image 91
tstanisl Avatar answered Sep 17 '25 10:09

tstanisl