Iterating over same type struct members in C

后端 未结 7 581
醉酒成梦
醉酒成梦 2020-12-10 20:06

Is it possible to iterate of a C struct, where all members are of same type, using a pointer. Here\'s some sample code that does not compile:

#include 

        
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 20:37

        int* tmp = &data->mem1 ;  // explicitly get the address of the first int member
    

    As you say, you have to be careful of alignment and other memory layout issues. You should be fine doing this with ints though.

    But I would question how readable this would make your code.

    Incidently,

        tmp += ( i * sizeof(foo) ) ;
    

    I do not think that does what you think it does, but I'm not entirely sure what you want it to do. Use ++tmp; if you want to step to the next int member of the same foo object.

提交回复
热议问题