Tag: C programming, struct, union, data structures

  • What Is the Difference Between struct and union in C?

    Introduction

    Structures and unions are user-defined data types in C that group different variables under one name. However, their behavior differs significantly…

    struct

    A struct allocates separate memory for each member. Example:

    struct Employee {
        int id;
        char name[50];
        float salary;
    };

    union

    A union shares memory among its members, so only one member can be used at a time. Example:

    union Data {
        int i;
        float f;
        char str[20];
    };

    Key Differences

    Aspect struct union
    Memory Allocates memory for all members Allocates shared memory for all members
    Usage For grouping related data For memory-efficient handling of variables