0
0
Cprogramming~30 mins

Why dynamic memory is needed - See It in Action

Choose your learning style9 modes available
Why Dynamic Memory is Needed
📖 Scenario: Imagine you are building a program that stores names of students in a class. Sometimes the class size changes, and you don't know the number of students before running the program.
🎯 Goal: You will create a simple C program that uses dynamic memory to store student names. This will show why dynamic memory is needed when the amount of data is not fixed.
📋 What You'll Learn
Create a pointer to hold student names dynamically
Use malloc to allocate memory for 3 student names
Add a variable to store the number of students
Use a loop to assign names to the allocated memory
Print the stored student names
💡 Why This Matters
🌍 Real World
Programs often need to handle data that changes size, like user input lists or files. Dynamic memory helps manage this efficiently.
💼 Career
Understanding dynamic memory is essential for C programmers working on system software, embedded devices, or performance-critical applications.
Progress0 / 4 steps
1
Create a pointer for student names
Declare a pointer called students of type char ** to hold multiple student names.
C
Need a hint?

Use char **students; to declare a pointer to an array of strings.

2
Set number of students and allocate memory
Create an integer variable called num_students and set it to 3. Then use malloc to allocate memory for students to hold 3 pointers to char.
C
Need a hint?

Use malloc to allocate memory for 3 pointers to strings.

3
Allocate memory for each student name and assign names
Use a for loop with variable i from 0 to num_students - 1. Inside the loop, allocate memory for each student name to hold 20 characters using malloc. Then assign these exact names: "Anna", "Ben", "Cara" to students[0], students[1], and students[2] respectively using strcpy.
C
Need a hint?

Use a loop to allocate memory for each name, then use strcpy to copy the names.

4
Print the student names
Use a for loop with variable i from 0 to num_students - 1. Inside the loop, print each student name stored in students[i] using printf.
C
Need a hint?

Use a loop and printf to show each name.