Structures and bitwise operations
This is related to two of my previous posts.
http://cboard.cprogramming.com/showthread.php?t=78726
http://cboard.cprogramming.com/showthread.php?t=78725
I got some flak for using ugly casting to hack into the address of a member structure of a class.
So I revised it somewhat and here is what I plan to do.
I have a structure all of whose member variables are bitfields:
Code:
struct x
{
UINT a:1;
...
UINT n:1;
};
The structure above is invoked in a class definition:
Code:
class y
{
public:
x some_str;
};
What I need to do is compare two classes by seeing how they differ in terms of the member structures. I could of course do it one by one
Code:
int comp[n];
int[0] = y_inst_a.some_str.a ^ y_inst_a.some_str.a;
...
int[n-1] = y_inst_a.some_str.n ^ y_inst_a.some_str.n;
First, the above is too long, and at the moment, I don't really know how many member variables I need in the structure at the moment.
Initially, I just accessed the memory of the structure directly to initialize and invoke its value:
Code:
//At the moment, the structure has less than eight values so I think using an unsigned character to represent it might be safe.
//constructor
y(){*(unsigned char*)(&some_str) = 0;}
unsigned char* val(){return (unsigned char*)&some_str;}
The most obvious worry is that the data could be corrupted around the stack but maybe there are tons more stuff I should be worried about (I'm not very experienced).
So after racking my brain a bit, the safest solution seemed to be to define an unsigned character and use that as the dumping ground for the structure values.
Code:
class y
{
public:
y(){some_str = (x*)&c;}
x* some_str; //it's a pointer this time
char c;
};
I haven't compiled the above yet so I don't know if it'll crash or not, but I really can't see a problem with it.
If the above "hack" is problematic, could anyone help me out as to how I could make the class comfortable use but safe as well?