GCGY Beta v1.0.1
GrowCodeEngineering
← Back to Hub
Back to Topics
c / c-fundamentals
20 mins

C Level 7: Structs, Typedef & Pointer Access (->)

Why This Matters: Structs allow programmers to define complex custom data models grouping related heterogeneous fields.
## Structures & The Arrow Operator

A `struct` groups related variables under a single custom record type.

```c
typedef struct {
    int id;
    char name[50];
    float gpa;
} Student;

Student s1 = {101, "Alice", 3.95};

// Access via pointer using arrow operator (->)
Student *ptr = &s1;
printf("ID: %d
", ptr->id); // Equivalent to (*ptr).id
```
MENTAL MODEL & MEMORY LAYOUT
STRUCT IN MEMORY:
Student s1 (0x3000):
[ id (4B) ][ name (50B) ][ gpa (4B) ]
     ▲
     │ Arrow Operator (ptr->id)
ptr (0x3000)
COMMON PITFALLS TO AVOID
  • Using dot operator `.` on struct pointers instead of arrow operator `->`.
  • Forgetting semicolon `;` at end of struct definition.
Struct Pointer Selection
#include <stdio.h>

typedef struct {
    int x;
    int y;
} Point;

void move(Point *p, int dx, int dy) {
    p->x += dx;
    p->y += dy;
}

int main() {
    Point pt = {10, 20};
    move(&pt, 5, 5);
    printf("Point: (%d, %d)\n", pt.x, pt.y);
    return 0;
}

Mutates struct fields inside function using struct pointer arrow operator `->`.

CONCEPT MASTERY CHECKPOINT

When accessing a struct field through a pointer `Student *ptr`, which operator is used?

NEXT RECOMMENDED LESSON
C Level 8: File Handling & Streams
Continue Path
Challenge: Define a struct `Rectangle` with width and height, and print the calculated area.
C Level 7: Structs, Typedef & Pointer Access (->)
1
2
3
4
5
6
7
8
9
10
11
12
13
No test case execution results available yet. Click "Run Code" to evaluate your solution.