Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pointer of specific bit size

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).

like image 779
user1205577 Avatar asked Jun 19 '12 11:06

user1205577


People also ask

How big is a pointer on a 64-bit machine?

In 64-bit data models, pointer sizes are always 64 bits.

Can you use sizeof on pointer?

The sizeof( ) operator is used to find the memory occupied by a data type, an expression, or a pointer.

Why is pointer size 4 bytes in C?

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.


2 Answers

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. ....

like image 63
Alok Save Avatar answered Sep 30 '22 01:09

Alok Save


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.

like image 43
dirkgently Avatar answered Sep 30 '22 00:09

dirkgently