Objects → Structs
Grouping related data
Introduction
In this lesson, you'll learn about objects → structs in C. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with grouping related data.
C has its own approach to grouping related data, which we'll explore step by step.
The C Way
Let's see how C handles this concept. Here's a typical example:
#include <stdio.h>
#include <string.h>
/* Struct — data only, no methods */
typedef struct {
char name[50]; /* fixed-size string buffer */
int age;
} Person;
/* Functions that operate on structs */
void person_greet(const Person *p) {
printf("Hi, I'm %s\n", p->name);
}
void person_birthday(Person *p) {
p->age++;
}
int main() {
Person p;
strncpy(p.name, "Alice", sizeof(p.name) - 1);
p.name[sizeof(p.name) - 1] = '\0';
p.age = 30;
person_greet(&p); /* pass address */
person_birthday(&p);
printf("Now %d\n", p.age);
}Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
const person = { name: "Alice", age: 30 };
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() { return "Hi, " + this.name; }
}
const p = new Person("Alice", 30);You may be used to different syntax or behavior.
C structs are pure data — no methods, no inheritance
You may be used to different syntax or behavior.
C strings in structs are fixed-size char buffers; JS uses dynamic strings
You may be used to different syntax or behavior.
C functions on structs take pointer params; JS has this
You may be used to different syntax or behavior.
Use -> for pointer-to-struct field access; . for value
Step-by-Step Breakdown
1. Data Only
C structs hold data fields only. Functions are defined separately and take a struct pointer — like a manual 'this'.
class Person { constructor(n, a) { this.name=n; this.age=a; } greet() {...} }typedef struct { char name[50]; int age; } Person;
void person_greet(const Person *p) { ... }2. Arrow vs Dot
Use . to access fields of a struct value. Use -> when you have a pointer to a struct (equivalent to (*p).field).
Person val; val.age = 30;
Person *ptr = &val; ptr->age = 31; /* same as (*ptr).age */3. String Buffers
Structs can't contain dynamic strings — use fixed char arrays. Always use strncpy to prevent buffer overflows.
strncpy(p.name, "Alice", sizeof(p.name) - 1);
p.name[sizeof(p.name) - 1] = '\0'; // ensure null terminationCommon Mistakes
When coming from JavaScript, developers often make these mistakes:
- C structs are pure data — no methods, no inheritance
- C strings in structs are fixed-size char buffers; JS uses dynamic strings
- C functions on structs take pointer params; JS has this
Key Takeaways
- C structs are data-only; no methods or inheritance
- Functions take struct pointers as their 'this'
- . for value access; -> for pointer access
- String fields are fixed char arrays; use strncpy