0
0
Cprogramming~20 mins

realloc function - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the realloc Function in C
📖 Scenario: You are managing a list of daily temperatures stored in a dynamic array in C. Sometimes, you need to add more days to the list, so you must resize the array safely.
🎯 Goal: Learn how to use the realloc function to resize a dynamic array in C while preserving existing data.
📋 What You'll Learn
Create a dynamic array of integers with initial size 3
Create a variable new_size to hold the new size of the array
Use realloc to resize the array to new_size
Print all elements of the resized array
💡 Why This Matters
🌍 Real World
Dynamic arrays are useful when you don't know the exact amount of data in advance, like reading sensor data or user input.
💼 Career
Understanding memory management and resizing arrays is important for systems programming, embedded development, and performance-critical applications.
Progress0 / 4 steps
1
Create the initial dynamic array
Write code to create a dynamic array called temps of integers with initial size 3 using malloc. Initialize the array with values 20, 22, and 19.
C
Need a hint?

Use malloc to allocate memory for 3 integers and assign it to temps. Then assign values to each index.

2
Create a new size variable
Add a variable called new_size and set it to 5 to represent the new size of the array.
C
Need a hint?

Declare an integer variable new_size and assign it the value 5.

3
Resize the array using realloc
Use realloc to resize the temps array to new_size. Assign the result back to temps. Then initialize the new elements temps[3] and temps[4] with values 21 and 23.
C
Need a hint?

Use temps = realloc(temps, new_size * sizeof(int)) to resize. Then assign values to the new indexes.

4
Print all elements of the resized array
Use a for loop with variable i from 0 to new_size - 1 to print each element of temps on its own line. Then free the allocated memory.
C
Need a hint?

Use a for loop to print each element with printf. Don't forget to call free(temps) at the end.