🧠 Lesson 8: Arrays & Memory Management
⏱️ Estimated time: 35 minutes | Difficulty: Intermediate
Direct Access
In C, you have direct control over memory. This is powerful but requires care to avoid bugs like memory leaks.
What Are Pointers?
A pointer is a variable that stores the memory address of another variable. Pointers are one of C's most powerful features!
#include <stdio.h>
int main() {
int age = 25;
int *ptr = &age; // ptr stores the ADDRESS of age
printf("Value: %d\n", age); // 25
printf("Address: %p\n", &age); // 0x7ffc...
printf("Pointer: %p\n", ptr); // Same address
printf("Deref: %d\n", *ptr); // 25 (dereference)
*ptr = 30; // Change value through pointer
printf("Age: %d\n", age); // 30!
return 0;
}
Analogy: Think of a pointer as a house address written on paper. The paper (pointer) isn't the house (value) — it just tells you WHERE the house is. `*ptr` means "go to the house at this address."
Pointers and Arrays
int arr[] = {10, 20, 30, 40, 50};
int *p = arr; // Array name IS a pointer!
printf("%d\n", *p); // 10 (first element)
printf("%d\n", *(p + 1)); // 20 (second element)
printf("%d\n", *(p + 2)); // 30 (third element)
// Pointer arithmetic
for (int *ptr = arr; ptr < arr + 5; ptr++) {
printf("%d ", *ptr);
}
Dynamic Memory Allocation
#include <stdlib.h>
// Allocate memory for 5 integers
int *arr = (int *)malloc(5 * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Use the memory
for (int i = 0; i < 5; i++) {
arr[i] = (i + 1) * 10;
}
// Always free when done!
free(arr);
⚠️ Memory Leak! Always free() dynamically allocated memory. Forgetting to
free causes memory leaks, which can crash your program!
Structs
struct Student {
char name[50];
int age;
float gpa;
};
int main() {
struct Student s1 = {"Alice", 20, 3.8};
printf("Name: %s\n", s1.name);
printf("Age: %d\n", s1.age);
printf("GPA: %.1f\n", s1.gpa);
// Pointer to struct
struct Student *ptr = &s1;
printf("Name: %s\n", ptr->name); // Arrow operator
return 0;
}
✅ Quick Quiz
❓ What does * do in front of a pointer?
❓ What function allocates memory dynamically?
❓ How do you access struct members via pointer?