Is there any way to loop through a struct with elements of different types in C?

Viewed 34032

my struct is some like this

typedef struct {
  type1 thing;
  type2 thing2;
  ...
  typeN thingN;
} my_struct 

how to enumerate struct childrens in a loop such as while, or for?

5 Answers

For the reference, you can loop through struct elements using pointer arithmetic, if they are the same type:

typedef struct numbers{
    int a;
    int b;
    int c;
} numbers;

numbers nums;

nums.a = 42;
nums.b = 99;
nums.c = 23;

int count = sizeof(nums) / sizeof(int);  // 3

for(int i=0; i < count; i++){
    printf("%d ", *(&nums.a + i) );      // start on the first field's address
}
Related