Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create a C program that demonstrates dynamic allocation of structs using malloc(). Your program should:

  1. Define a struct named Car with the following members:
    • An integer year to store the manufacturing year
    • A character array brand with size 20 to store the car brand
    • A character array model with size 25 to store the car model
    • A float price to store the car price
    • An integer mileage to store the car's mileage
  2. In the main function, declare a pointer to a Car struct named carPtr
  3. Use malloc() to dynamically allocate memory for one Car struct and assign the returned address to carPtr
  4. Check if the memory allocation was successful:
    • If carPtr is NULL, print Memory allocation failed and exit the program
    • If allocation succeeded, print Memory allocation successful
  5. 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
  6. 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
  7. 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] years
    • Current Value: [current_value]
  8. Free the dynamically allocated memory using free(carPtr)
  9. 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;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow