Meloun
Meloun

Reputation: 15099

How to iterate thorough all items in a structure?

I have for example this format of the structure

typedef struct{
  tMY_STRUCT2 my_struct2;
  u16 item1;
  u8 item2[20];      
  u32 item3;
}tMY_STRUCT;

How can I get through the structure? Because of alignment its not so easy and I cant just calc the offset from begin the structure with SIZEOF(item).

Is there any way?

Reason: I need to initiate large structure, there are some conditions for that, so I need to make it within a FOR cycle.

Upvotes: 2

Views: 165

Answers (2)

Patrick
Patrick

Reputation: 8318

I don't quite understand how a for loop is going to help you here... however there is no nice way to iterate through a structure.

You could set up a structure of pointers to the objects in your struct and then skip through that by sizeof( ptr ) but that would be horrible and your co-workers will lynch you.

Upvotes: 0

djechlin
djechlin

Reputation: 60788

Don't do this. The point of a structure is you can't handle its data items uniformly. Structure is to heterogeneous data as array is to homogeneous.

Init each field one at a time in the code or init the whole struct to zero. Those are the only good practice options. Alignment in particular will depend on machine architecture, compiler etc. so an approach that uses this will likely break if you make seemingly trivial changes to your code, such as reordering the fields in the declaration, or run on a different OS or compile somewhere else.

Options:

memset(mystruct, 0, sizeof(mystruct));

or (I think this is C99) mystruct_t foo = {0};

Or just init each field.

Upvotes: 5

Related Questions