Structures and Unions in C

 Structures and Unions in C


Structures and unions allow you to define custom data types by grouping together multiple variables of different types. Structures are used to group related data elements, while unions allow different types of data to share the same memory space.



#include <stdio.h>


struct Point {

    int x;

    int y;

};


union Data {

    int intValue;

    float floatValue;

    char stringValue[20];

};


int main() {

    struct Point p;

    p.x = 3;

    p.y = 5;

    printf("Point coordinates: (%d, %d)\n", p.x, p.y);


    union Data data;

    data.intValue = 42;

    printf("Integer value: %d\n", data.intValue);

    data.floatValue = 3.14;

    printf("Float value: %.2f\n", data.floatValue);

    strcpy(data.stringValue, "Hello");

    printf("String value: %s\n", data.stringValue);


    return 0;

}

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...