Dynamic Allocation of Structs
Part of the Logic & Flow section of Coddy's C journey — lesson 48 of 63.
So far, you've learned how to create structs on the stack - they exist within the scope where they're declared and are automatically cleaned up when that scope ends. But what if you need a struct to persist beyond its original scope, or when you don't know at compile time how many structs you'll need?
This is where dynamic allocation comes in. You can use malloc() to create structs on the heap, just like you would for any other data type. The key difference is that dynamically allocated structs remain in memory until you explicitly free them with free().
Here's the syntax for dynamically allocating a struct:
struct Point *ptr = malloc(sizeof(struct Point));This allocates enough memory on the heap to hold one Point struct and returns a pointer to that memory. You can then use the arrow operator to access and modify the struct members:
ptr->x = 10;
ptr->y = 20;Remember to always check if malloc() succeeded (returned non-NULL) and to call free(ptr) when you're done with the struct to prevent memory leaks. This technique is essential for building flexible programs that can create and manage data structures at runtime.
Challenge
EasyCreate a C program that demonstrates dynamic allocation of structs using malloc(). Your program should:
- Define a
structnamedCarwith the following members:- An integer
yearto store the manufacturing year - A character array
brandwith size 20 to store the car brand - A character array
modelwith size 25 to store the car model - A float
priceto store the car price - An integer
mileageto store the car's mileage
- An integer
- In the main function, declare a pointer to a
Carstruct namedcarPtr - Use
malloc()to dynamically allocate memory for oneCarstruct and assign the returned address tocarPtr - Check if the memory allocation was successful:
- If
carPtrisNULL, printMemory allocation failedand exit the program - If allocation succeeded, print
Memory allocation successful
- If
- Read the following input values and assign them to the struct members using the arrow operator:
- Read an integer for the year and assign it using
carPtr->year - Read a string for the brand and assign it using
carPtr->brand - Read a string for the model and assign it using
carPtr->model - Read a float for the price and assign it using
carPtr->price - Read an integer for the mileage and assign it using
carPtr->mileage
- Read an integer for the year and assign it using
- After reading all values, perform the following calculations using the arrow operator:
- Calculate the car's age by subtracting the year from 2024:
int age = 2024 - carPtr->year; - Calculate depreciation rate based on age: if age is greater than 10, set depreciation to 0.6, otherwise set it to 0.8
- Calculate current value:
carPtr->price * depreciation
- Calculate the car's age by subtracting the year from 2024:
- Print the car information using the arrow operator in this exact format:
Car Information:Year: [year]Brand: [brand]Model: [model]Original Price: [price]Mileage: [mileage]Age: [age] yearsCurrent Value: [current_value]
- Free the dynamically allocated memory using
free(carPtr) - Print
Memory freed successfully
This challenge tests your understanding of dynamic struct allocation using malloc(), checking for allocation failure, accessing struct members through pointers using the arrow operator, and properly freeing allocated memory with free(). You'll practice the complete lifecycle of dynamic memory management with structs.
Cheat sheet
Use malloc() to dynamically allocate structs on the heap:
struct Point *ptr = malloc(sizeof(struct Point));Access struct members through pointers using the arrow operator:
ptr->x = 10;
ptr->y = 20;Always check if malloc() succeeded and free the memory when done:
if (ptr == NULL) {
// Handle allocation failure
}
// Use the struct...
free(ptr);Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// TODO: Define the Car struct here
int main() {
// TODO: Declare a pointer to Car struct named carPtr
// TODO: Use malloc() to allocate memory for one Car struct
// TODO: Check if memory allocation was successful
// Read input values
int year, mileage;
char brand[20], model[25];
float price;
scanf("%d", &year);
scanf("%s", brand);
scanf("%s", model);
scanf("%f", &price);
scanf("%d", &mileage);
// TODO: Assign input values to struct members using arrow operator
// TODO: Calculate age, depreciation, and current value
// TODO: Print car information in the required format
// TODO: Free the allocated memory and print success message
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions