C Programming

⌘K
  1. Home
  2. Docs
  3. C Programming
  4. Structure and Union
  5. Introduction to Structure and Union

Introduction to Structure and Union

A structure in C is a user-defined data type that allows grouping variables of different data types under one name. It is used to represent a record.

  • Useful when you need to store multiple data items of different types together.

Structure Declaration Syntax:

struct StructureName {
    data_type member1;
    data_type member2;
    ...
};

Example:

struct Student {
    int id;
    char name[50];
    float marks;
};

Structure Initialization:

struct Student s1 = {1, "John", 85.5};

Or initialize members individually:

struct Student s2;
s2.id = 2;
strcpy(s2.name, "Alice");
s2.marks = 90.0;
  • Note: #include <string.h) is needed for strcpy().

Example Code for Structure:

#include <stdio.h>
#include <string.h>

struct Student {
    int id;
    char name[50];
    float marks;
};

int main() {
    struct Student s1 = {1, "John", 92.5};

    printf("ID: %d\n", s1.id);
    printf("Name: %s\n", s1.name);
    printf("Marks: %.2f\n", s1.marks);

    return 0;
}

A union is similar to a structure in syntax, but with a key difference:

  • In a union, all members share the same memory location.
  • Only one member can hold a value at a time.

Union Declaration Syntax:

union UnionName {
    data_type member1;
    data_type member2;
    ...
};

Example:

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

Union Initialization:

union Data d1;
d1.i = 10;      // Assign value to integer member

d1.f = 3.14;    // Overwrites previous value

strcpy(d1.str, "Hello");  // Overwrites again
  • Only the last written member holds valid data, since all members share the same memory.

Example Code for Union:

#include <stdio.h>
#include <string.h>

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

int main() {
    union Data d;

    d.i = 10;
    printf("d.i = %d\n", d.i);

    d.f = 3.14;
    printf("d.f = %.2f\n", d.f);  // d.i is now invalid

    strcpy(d.str, "Hello");
    printf("d.str = %s\n", d.str);  // d.f is now invalid

    return 0;
}

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *