Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c define arrays in struct with different sizes

Tags:

c

struct

I need to define a struct for two types of objects. Both have exactly the same data structure and perform same tasks (member methods).

The ONLY difference is that the array sizes are different in the two types, one using SIZE_A, the other SIZE_B.

Duplicating the definition of the struct and functions is not wanted.

How could I use one type of 'struct', and initialize its arrays with different sizes?

#define SIZE_A 100
#define SIZE_B 200

typedef struct{
  int matr[SIZE_A][SIZE_A];  // for another type matr[SIZE_B]
  int arr[SIZE_A];           // for another type arr[SIZE_B]
  int size;                  // will be initialized to SIZE_A or SIZE_B
  int var1, var2;
}s;

void task1(s* si){
  ...
}

void task2(s* si){
  ...
like image 398
lukmac Avatar asked Oct 26 '25 07:10

lukmac


1 Answers

Even with a union, the struct will be as big as the largest of the two arrays.

Do one of these:

  1. Ignore the overhead of the biggest array size. (Use one array or a union)
  2. Create a separate struct for each type.
  3. Dynamically allocate the array with malloc.
like image 156
Justin Meiners Avatar answered Oct 27 '25 21:10

Justin Meiners



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!