0

I would like to create a struct that contains a bidimensional array in C, but I don't know how to initialize it because I don't know the dimensions. Is there a way to do it?

struct myStruct {
      int m[][];
};
emaqui
  • 11
  • 1

2 Answers2

0

If the outer most dimension is known at the compile time then you can declare the structure with a flexible array member like for example

#define N 10
//...
struct myStruct {
      size_t m;
      int a[][N];
};

Otherwise instead of the array you should use a pointer of the type int **

struct myStruct {
      size_t m;
      size_t n;
      int **a;
};

where data members m and n are used to specify dimensions of the allocated dynamically arrays using the pointer a.

In both cases arrays are allocated dynamically.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-1

You can allocate it some amount of memory, for example 5 times 5 using malloc and then reallocate in case it's not enough.

E.g.:

int *m= (int *)malloc(rows * cols * sizeof(int));
Lubos
  • 39
  • 5