> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# C Struct

A `struct` (structure) in C is a user-defined, composite data type that aggregates variables of potentially different data types into a single, contiguous block of memory. Each variable within a structure is referred to as a member or field. Unlike arrays, which require all elements to be of the same type, structures allow for heterogeneous data grouping.

## Syntax and Declaration

The `struct` keyword is used to define the layout of the structure. The optional identifier following the keyword is called the **structure tag**.

```c theme={"dark"}
struct [structure_tag] {
    data_type member1;
    data_type member2;
    /* ... */
} [optional_variable_list];
```

Defining a structure creates a new data type but does not allocate memory. Memory is only allocated when a variable of that structure type is instantiated.

```c theme={"dark"}
// Structure definition
struct SensorData {
    int id;
    float temperature;
    char status;
};

// Variable instantiation
struct SensorData reading1;
```

## Initialization

Structures can be initialized at the time of declaration. C99 introduced **designated initializers**, which allow members to be initialized by name in any order, improving readability and safety.

```c theme={"dark"}
// Standard initialization (order-dependent)
struct SensorData reading1 = { 101, 25.5f, 'A' };

// Designated initialization (C99, order-independent)
struct SensorData reading2 = {
    .temperature = 22.1f,
    .status = 'B',
    .id = 102
};

// Partial initialization (unspecified members are zero-initialized)
struct SensorData reading3 = { .id = 103 }; 
```

## Member Access

Members of a structure are accessed using two distinct operators, depending on whether you are working with the structure directly or via a pointer.

1. **Dot Operator (`.`)**: Used when accessing members of a direct structure variable.
2. **Arrow Operator (`->`)**: Used when accessing members through a pointer to a structure. It implicitly dereferences the pointer.

```c theme={"dark"}
struct SensorData reading;
struct SensorData *ptr = &reading;

// Direct access
reading.id = 1;

// Pointer access
ptr->temperature = 24.0f;

// The arrow operator is syntactic sugar for:
(*ptr).status = 'C';
```

## Memory Layout and Alignment

Structure members are allocated in memory in the exact order they are declared. However, the total size of a structure is rarely the exact sum of the sizes of its members due to **data structure alignment** and **padding**.

Compilers insert invisible padding bytes between members to ensure that each member aligns to memory addresses optimal for the target CPU architecture (typically multiples of the member's size).

```c theme={"dark"}
struct Payload {
    char type;      // 1 byte
                    // 3 bytes of padding inserted here
    int value;      // 4 bytes
    char flag;      // 1 byte
                    // 3 bytes of padding inserted here
};
```

In the example above, `sizeof(struct Payload)` will typically evaluate to `12` bytes, not `6` bytes. To prevent the compiler from inserting padding, compiler-specific directives such as `__attribute__((packed))` (GCC/Clang) or `#pragma pack` (MSVC) must be used, though this may incur a performance penalty during memory access.

## Typedef Integration

To avoid repeatedly typing the `struct` keyword during variable declaration, `typedef` is commonly used to create a type alias.

```c theme={"dark"}
// Anonymous struct aliased to 'Vector3'
typedef struct {
    float x;
    float y;
    float z;
} Vector3;

// Instantiation without the 'struct' keyword
Vector3 velocity = { 1.0f, 0.0f, -1.0f };
```

## Bit-Fields

Structures support **bit-fields**, allowing developers to specify the exact number of bits a member should occupy. This is strictly used for memory optimization and mapping hardware registers.

```c theme={"dark"}
struct Register {
    unsigned int enable : 1;  // Occupies 1 bit
    unsigned int mode   : 3;  // Occupies 3 bits
    unsigned int status : 4;  // Occupies 4 bits
};
```

*Note: The address-of operator (`&`) cannot be applied to a bit-field member, as bit-fields may not start on a byte boundary.*

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor C Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
