-1

I am currently trying to iterate through a struct var in C++. I've got a struct var but I need to access specific elements of the struct.

someStruct {
     int a;
     int b;
     bool c;
     ...
};

&someStructVar+1 would increase the memory by the size of the struct. But I need to increase the memory address by one bit after another. Is this possible? Is there any other approach?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Lynguistic
  • 141
  • 1
  • 2
  • 9
  • 2
    Iterating over elements like this using pointers is a recipe for disaster. Are you sure you know how they were packed into that structure? Do you know for sure what padding was used to get them to align properly? – tadman Aug 10 '17 at 18:54
  • Minimal addressable unit in C is byte, not bit, so you cannot do it. – Sergey Kalinichenko Aug 10 '17 at 18:54
  • @dasblinkenlight, that's not the only problem :) – SergeyA Aug 10 '17 at 18:57
  • 1
    @SergeyA it seems to be the only problem of that question. That said, it is unclear how iterating individual bits relates to iterating "elements". The question is either two different questions mixed together, both of which have their own problems. Or one of the questions is a ghost created by confused terminology. – eerorika Aug 10 '17 at 19:01
  • Do you want to the iterate through the struct one byte after another, or one member after another? The post marked as duplicate addresses the question of how to iterate through the members one after the other, not the bytes one after the other. – R Sahu Aug 10 '17 at 19:01
  • I want to iterate member after member and my try is to use pointer. Thus addresses of the struct members differs by one to eight bits I want to increase a pointer by one bit. The setting is that I want to create a generic request for one specific struct parameter.I only know the bit offset of the parameter. – Lynguistic Aug 11 '17 at 05:15

2 Answers2

0

What you're asking for is reflection, which C does not support. You can't get a list of fields of a struct and iterate through them.

You'll need to explicitly call out each field by name.

dbush
  • 205,898
  • 23
  • 218
  • 273
-1

You can't "iterate" members of struct through pointer arithemetics, this is not allowed in C++.

The only thing you can iterate with pointer arithemtics are C-style arrays.

SergeyA
  • 61,605
  • 5
  • 78
  • 137