Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy access to multiple struct arrays

I have 2 struct arrays

myStruct leds_left[20];
myStruct leds_right[20];

I need a way to combine the two structs, so that I can use it like:

*(structPtr[10]) // points to element of leds_left[10]
*(structPtr[30]) // points to element of leds_right[10] 

I already tried the following:

myStruct ** structPtr = (myStruct**) malloc((20 + 20) * sizeof(myStruct*));
structPtr[0] = &leds_right[15]; //just with one element for testing

*(structPtr[0]) = newValue;

What am I doing wrong?

like image 502
shout Avatar asked Nov 25 '25 01:11

shout


1 Answers

To be sure that leds_left and leds_right are really allocated in consecutive memory they must be "structured together". This in combination with a union could provide what you want:

#include <stdio.h>

typedef struct { int i; /* ... */ } myStruct;

static union {
  struct {
    myStruct leds_left[20];
    myStruct leds_right[20];
  };
  myStruct leds_all[40];
} data;

int main()
{
  for (int i = 0; i < 20; ++i) {
    data.leds_left[i].i = 1 + i;
    data.leds_right[i].i = -(1 + i);
  }
  for (int i = 0; i < 40; ++i) {
    printf(" %d", data.leds_all[i].i);
  }
  printf("\n");
  return 0;
}

Compiled and tested with gcc in cygwin on Windows 10 (64 bit):

$ gcc -std=c11 -o test-struct-array test-struct-array.c 

$ ./test-struct-array.exe 
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20

$

Attention!

Packing and alignment could become an issue (depending on what components myStruct actually contains).

like image 159
Scheff's Cat Avatar answered Nov 27 '25 14:11

Scheff's Cat



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!