Structures and Unions in C Programming

Learn the key differences between Structures and Unions in C, their memory management, and efficient data handling in C programming.

Structures and Unions in C Programming
Structures and Unions in C Programming 

Structures

In C language a Structure is a collection of different type of data , store in a single name Structure can hold dissimilar data.

Example: time = hours, minutes, second.

Student: name, roll no, class, marks.

Other

Structure is a user defined data type that allows different data type to be combined together to represent a data record.

Declaration 

struct Structure Name {
    data type member_1;
    data type member_2;
    ...
};

Example 
#include <stdio.h>
struct Student {        // Defining a structure
    char name[20];
    int age;
    float marks;
};
int main() {
    struct Student s1 = {"Rahul", 20, 85.5}; /*Initializing structure*/
    printf("Name: %s\n", s1.name);      /*Accessing structure members*/
    printf("Age: %d\n", s1.age);
    printf("Marks: %.2f\n", s1.marks);
    return 0;
}
Output 

Name: Rahul
Age: 20
Marks: 85.50

Unions 

In C language a union is a user-defined data type that allows multiple variables of different types to share the same memory location.

Declaration 

union Union Name {
    data_type member_1;
    data_type member_2;
    ...
};

Example 
#include <stdio.h>
union Data {     // Defining a union
    int x;
    float y;
    char ch;
};
int main() {
    union Data d;
    d.x = 10;
    printf("x: %d\n", d.x);
    d.y = 5.5;
    printf("y: %.2f\n", d.y); // x is now overwritten
    d.ch = 'A';
    printf("ch: %c\n", d.ch); // y is now overwritten
    return 0;
}
Output 

x: 10
y: 5.50
ch: A

Post a Comment