Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to C
C Structures and Unions

C Structures and Unions

C2,594 viewsBy Admin
cstructuresunions

Structures

A struct groups related variables of different types into one custom type.

struct Point {
    int x;
    int y;
};

struct Point p = {10, 20};
printf("%d, %d", p.x, p.y); // 10, 20

typedef for Cleaner Code

typedef struct {
    char name[50];
    int age;
} Person;

Person sara = {"Sara", 25};

Unions

A union stores different types in the same memory — only one member is valid at a time, saving memory.

union Value {
    int i;
    float f;
    char c;
};
// sizeof(union) = size of its largest member

Struct vs Union

StructUnion
MemorySum of membersLargest member
Members usableAll at onceOne at a time

FAQs

When use a union?

When a value can be one of several types but never more than one at a time — saves memory. More in our C guides.

Access struct via pointer?

Use the arrow operator: ptr->x.