Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 746
drigoSkalWalker Avatar asked Nov 23 '09 17:11

drigoSkalWalker


People also ask

Can you loop through a struct?

You can iterate through an array of structs but not the struct members. Learn about Classes. You have a struct with function as well as data members. You can add functions to structs too, but it's best to learn the whole shtick.

How do you access the structure members of a for loop?

Members in structs are designed to be accessed by name, as opposed to elements in arrays which are designed to be indexed. Computing addresses from offsets is a possibility but you still need to know the struct layout anyway — and on top, that layout can change with a compiler option or pragma.

Can a struct have methods C?

Contrary to what younger developers, or people coming from C believe at first, a struct can have constructors, methods (even virtual ones), public, private and protected members, use inheritance, be templated… just like a class .


1 Answers

I'm not sure what you want to achieve, but you can use X-Macros and have the preprocessor doing the iteration over all the fields of a structure:

//--- first describe the structure, the fields, their types and how to print them #define X_FIELDS \     X(int, field1, "%d") \     X(int, field2, "%d") \     X(char, field3, "%c") \     X(char *, field4, "%s")  //--- define the structure, the X macro will be expanded once per field typedef struct { #define X(type, name, format) type name;     X_FIELDS #undef X } mystruct;  void iterate(mystruct *aStruct) { //--- "iterate" over all the fields of the structure #define X(type, name, format) \          printf("mystruct.%s is "format"\n", #name, aStruct->name); X_FIELDS #undef X }  //--- demonstrate int main(int ac, char**av) {     mystruct a = { 0, 1, 'a', "hello"};     iterate(&a);     return 0; } 

This will print :

mystruct.field1 is 0 mystruct.field2 is 1 mystruct.field3 is a mystruct.field4 is hello 

You can also add the name of the function to be invoked in the X_FIELDS...

like image 153
philant Avatar answered Oct 14 '22 10:10

philant