DEV Community

Ujjawal Chaudhary
Ujjawal Chaudhary

Posted on

Day 6: Structs in C: Organizing Data without Classes

In languages like Java or Python, you use Classes to bundle data together. C doesn't have Classes. It has something rawer: Structs.

A struct (Structure) is how we create custom data types.

Without structs, if I wanted to store a student's data, I'd have to manage separate variables:

  • char *name1
  • int age1
  • float gpa1

With structs, I can group them into a single Student type. This is the ancestor of the "Object" in Object-Oriented Programming.

The Code

Here is how we define and use a custom data type in C.



// Day 6: Grouping chaos into order

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

// Before: Messy variables scattered everywhere
// char *name1 = "Alice"; int age1 = 20;

// After: A custom Data Type
// We define a blueprint called "Student"
typedef struct {
    char name[50];
    int age;
    float gpa;
} Student;

int main() {
    // Now we treat the data as a single "Object"
    // We can initialize it just like an array
    Student s1 = {"Alice", 20, 3.8};

    // We access fields using the dot operator (.)
    printf("Name: %s\n", s1.name);
    printf("GPA:  %.2f\n", s1.gpa);

    return 0;
}


πŸ“‚ View the source code on GitHub:https://github.com/Ujjawal0711/30-Days
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
Β 
pauljlucas profile image
Paul J. Lucas β€’

This barely scratches the surface of how to use structs. Really, it shows nothing except the syntax .