Course contentsShow
← C
Lesson 652 of 1,2199. Structures and UnionsFree lesson

Limitations of bit-field addresses

Limitations of bit-field addresses

What you'll learn: Why you cannot use the address-of operator (&) or pointers to target specific bit-fields within a structure.

The "House vs. Room" Problem

In standard C programming, the smallest unit of memory we can address is a byte. Think of a byte like a house with its own unique street address. Normally, if you have a variable, it occupies at least one full "house," and you can point a finger (a pointer) directly at it.

Bit-fields are different. They allow us to pack multiple variables into a single byte to save space. Imagine splitting a single house into four tiny studio apartments. While the house still has a street address, the individual studios do not have their own unique mailboxes registered with the city.

In C, because a bit-field might only occupy 3 bits of an 8-bit byte, it doesn't have its own memory address. It is a "sub-tenant" of a larger memory slot.

Why the & operator fails

Since a pointer must point to a specific byte boundary, the compiler will throw an error if you try to take the address of a bit-field. You cannot create a int *ptr that points to a 3-bit segment of an integer.

#include <stdio.h>

struct Controller {
    unsigned int isOn : 1;  // Only 1 bit
    unsigned int mode : 3;  // Only 3 bits
};

int main() {
    struct Controller myConfig = {1, 5};

    // THIS WILL CAUSE A COMPILER ERROR:
    // scanf("%u", &myConfig.isOn); 
    
    // THIS WILL ALSO FAIL:
    // unsigned int *ptr = &myConfig.mode;

    printf("You can read it: %u", myConfig.mode);
    return 0;
}

Consequences for your code

This limitation leads to two practical rules:

  1. No Scans: You cannot pass a bit-field directly to scanf(), as that function requires the memory address of the destination.
  2. No Pointers: You cannot create arrays of bit-fields or point to them to manipulate them indirectly.

If you need to get the address of the data, you must point to the entire structure itself, rather than the tiny bit-fields hidden inside it. To modify a bit-field using a function, you have to pass the value, modify it, and assign it back, or pass a pointer to the parent struct.

Key takeaway

Bit-fields do not have individual memory addresses because they are smaller than the smallest addressable unit (a byte); therefore, you cannot use the & operator on them.