Structures

C structure definitions and usage

C basic structure

C basic structure definition and usage

#include <stdio.h>

struct Student {
    char name[50];
    int age;
    float grade;
};

int main() {
    struct Student student1 = {"Alice", 20, 85.5};
    
    printf("Name: %s\n", student1.name);
    printf("Age: %d\n", student1.age);
    printf("Grade: %.2f\n", student1.grade);
    
    return 0;
}
C structure with functions

C structure with function parameter

#include <stdio.h>

struct Rectangle {
    int width;
    int height;
};

int area(struct Rectangle r) {
    return r.width * r.height;
}

int main() {
    struct Rectangle rect = {10, 5};
    printf("Area: %d\n", area(rect));
    return 0;
}
C structure with pointer members

C structure with pointer members and dynamic allocation

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

struct Person {
    char *name;
    int age;
};

int main() {
    struct Person p;
    p.name = malloc(50);
    strcpy(p.name, "Alice");
    p.age = 25;
    
    printf("Name: %s, Age: %d\n", p.name, p.age);
    
    free(p.name);
    return 0;
}
C structure with nested structures

C structure with nested structures

#include <stdio.h>

struct Date {
    int day;
    int month;
    int year;
};

struct Student {
    char name[50];
    int age;
    struct Date birth_date;
};

int main() {
    struct Student s = {"John", 20, {15, 3, 2004}};
    
    printf("Name: %s\n", s.name);
    printf("Age: %d\n", s.age);
    printf("Birth Date: %d/%d/%d\n", s.birth_date.day, 
           s.birth_date.month, s.birth_date.year);
    
    return 0;
}