My question is about pointing to chunks of memory of an odd size.
Let's say I have a struct
declared like so:
typedef struct{
int32 val1 : 29;
int32 val2 : 26;
char val3;
}MyStruct;
Let's assume declaring specific bit fields in the struct is desireable (why we'd use the bit fields is not the question).
If I wanted to declare a pointer that points to one of those fields, I might try something like this:
MyStruct test;
int32 *myPtr = &(test.val1);
Except that this produces the error "taking the address of a bit field is not allowed".
Assuming that we would want to, is there a way to point to those fields in this way? I know that C++ will probably pad the fields to the next byte (which in this case would be 32 bits).
In 64-bit data models, pointer sizes are always 64 bits.
The sizeof( ) operator is used to find the memory occupied by a data type, an expression, or a pointer.
Size of a pointer is fixed for a compiler. All pointer types take same number of bytes for a compiler. That is why we get 4 for both ptri and ptrc.
In C++, the smallest addressable value must have a size of at least 1 byte. So No you cannot take address of an bit field with pointers.
C++03 Standard 9.6 Bit-fields:
Para 3:
...The address-of operator& shall not be applied to a bit-field, so there are no pointers to bit-fields. ....
Except that this produces the error "taking the address of a bit field is not allowed".
This is explicitly disallowed by the standard. See [class.bit] 9.6/3:
The address-of operator & shall not be applied to a bit-field, so there are no pointers to bitfields.
A byte (which is CHAR_BIT
bits wide, where CHAR_BIT
is at least 8) is the minimum you can address.
Assuming that we would want to, is there a way to point to those fields in this way?
No. You can have a pointer to an object of the enclosing struct
type though. This is a direct carry over from C; See C FAQ 2.26:
Bit-fields are inconvenient when you also want to be able to manipulate some collection of bits as a whole (perhaps to copy a set of flags).
You may want to look at other alternatives such std::bitset
or boost::dynamic_bitset
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With