01. Struct Declarations, Initializers & typedef

🟢 Difficulty: Beginner | Custom Composite Records, Member Dot Operator (.) & Type Aliases

📖 Definition

A structure (struct) in C is a composite data type that aggregates related variables of different primitive or custom types into a single memory block. Individual fields inside a structure are called members, accessed using the member selection dot operator (.).

🎯 Why It Is Used

  • Domain Entity Modeling: Modeling real-world entities (e.g. Student with id, name, gpa) rather than managing multiple loose disconnected arrays.
  • Clean Type Abstraction (typedef): Using typedef struct creates clean, concise type aliases (e.g. Point p1; instead of struct Point p1;).

⚙️ How It Works: Struct Memory Placement

Declaring a struct defines a blueprint in compiler memory. Instantiate variables reserves a contiguous RAM block large enough to contain all members in the exact order they were declared in the struct block (plus compiler padding bytes for alignment).

📝 Syntax

// 1. Standard Struct Declaration
struct Student {
    int roll_no;
    char name[32];
    double gpa;
};

// 2. Struct with typedef Alias
typedef struct {
    double x;
    double y;
} Point;

// 3. Member Access Dot Operator (.)
struct Student s1 = {101, "Alice", 3.85}; // Sequential Initialization
Point p1 = {.x = 12.5, .y = 45.0};        // C99 Designated Initialization

🔀 Initialization Patterns

  • Sequential Initialization: Values supplied in exact order of field declaration ({101, "Alice", 3.85}).
  • C99 Designated Initializers: Explicitly assigning named fields ({.gpa = 3.9, .roll_no = 102}), improving code readability and robustness when struct layout changes.

🌱 Beginner Example: Simple Student Record

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

struct Student {
    int id;
    char name[32];
    double gpa;
};

int main(void) {
    struct Student s1;

    s1.id = 1001;
    snprintf(s1.name, sizeof(s1.name), "Linus Torvalds");
    s1.gpa = 3.98;

    printf("=== Student Record ===\n");
    printf("ID   : %d\n", s1.id);
    printf("Name : %s\n", s1.name);
    printf("GPA  : %.2lf\n", s1.gpa);
    return 0;
}

🌼 Intermediate Example: Typedef Aliasing & Designated Initializers

#include <stdio.h>

typedef struct {
    double latitude;
    double longitude;
    const char *location_name;
} GPSCoordinate;

int main(void) {
    // C99 Designated Initializer
    GPSCoordinate mumbai = {
        .location_name = "Mumbai, India",
        .latitude = 19.0760,
        .longitude = 72.8777
    };

    printf("Location : %s\n", mumbai.location_name);
    printf("Latitude : %.4lf N\n", mumbai.latitude);
    printf("Longitude: %.4lf E\n", mumbai.longitude);
    return 0;
}

🌲 Advanced Example: Copying Structs via Value Assignment

#include <stdio.h>

typedef struct {
    int red;
    int green;
    int blue;
} RGBColor;

int main(void) {
    RGBColor primary = {255, 0, 0};

    // In C, assigning one struct variable to another performs a full bitwise copy!
    RGBColor copy = primary;

    // Mutating 'copy' does NOT alter 'primary'!
    copy.red = 200;

    printf("Primary Red Value: %d\n", primary.red); // Prints 255
    printf("Copy Red Value   : %d\n", copy.red);    // Prints 200
    return 0;
}

🔍 Line-by-Line Explanation

  • s1.id = 1001;: Uses member selection dot operator . to assign integer value to id field.
  • GPSCoordinate mumbai = { .latitude = 19.0760, ... };: C99 designated initializer explicitly mapping values to struct field names.
  • RGBColor copy = primary;: Performs an automatic shallow bitwise copy of all struct fields across memory.

💻 Expected Terminal Output

=== Student Record ===
ID   : 1001
Name : Linus Torvalds
GPA  : 3.98
Location : Mumbai, India
Latitude : 19.0760 N
Longitude: 72.8777 E
Primary Red Value: 255
Copy Red Value   : 200

⚠️ Common Mistakes & Pitfalls

  • Direct String Array Assignment: Writing s1.name = "Alice"; is invalid in C because array names are non-modifiable lvalues! Use snprintf(s1.name, sizeof(s1.name), "Alice"); instead.
  • Forgetting Trailing Semicolon After Struct Block: Omitting the trailing semicolon at the end of a struct declaration (struct X { ... };) causes syntax compilation errors.

📌 Important Rules & Limitations

  • Struct declarations must end with a trailing semicolon ;.
  • In C, struct assignment (s1 = s2) copies all member fields bitwise.

🌐 Multilingual Explanation: English

A struct groups heterogeneous variables into a single custom type. Members are accessed via the dot operator (.), and typedef creates clean type aliases.

🌐 Multilingual Explanation: Hindi (Roman Script)

struct alag-alag data types ke variables ko ek sath group karta hai. Elements ko access karne ke liye dot . operator aur type shortening ke liye typedef ka upyog karein.

🌐 Multilingual Explanation: Marathi (Roman Script)

struct vegveglya data types chya variables cha group karto. Fields access karnyasathi dot . operator vapra.

❓ Practice Questions

  1. What is the advantage of C99 designated initializers over sequential initializers for structs?
  2. Why does s1.name = "John"; fail to compile if name is declared as char name[20] inside a struct?
  3. How does typedef simplify struct variable declarations?

🚀 Practical Coding Challenge

Write a C program named bank_account_struct.c that defines a typedef struct BankAccount with fields for account_number, holder_name, and balance, creates two accounts, and transfers money between them.

🧭 Navigation & Breadcrumbs

← Module 13 Guide | Next: 02. Pointers to Structs & Arrow Operator →