

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 9
click for more info
Not enough gems
Cost: 6 gems
1: Low Level Stack
incomplete
2: Stack Push
incomplete
3: Stack Pop
incomplete
4: Stack free
incomplete
5: Dangerous Push
incomplete
6: Multiple Types
incomplete
This lesson's interactive features are locked, please to keep using them
Ok, so let's actually store some data instead of just allocating memory for no practical purpose (a.k.a "haskell programming").
As you know, our stack has a count and a capacity... but what happens when the count is equal to the capacity? We need to make room for more data!
We'll take a simple approach: whenever we run out of capacity, we'll double it. That way we don't have to reallocate memory on every push. For example:
| Count | Capacity | Data |
|---|---|---|
| 0 | 4 | [-, -, -, -] |
| 1 | 4 | [1, -, -, -] |
| 2 | 4 | [1, 2, -, -] |
| 3 | 4 | [1, 2, 3, -] |
| 4 | 4 | [1, 2, 3, 4] |
| 5 | 8 | [1, 2, 3, 4, 5, -, -, -] |
Complete the stack_push function. It safe(ish)ly adds a new object to the top of the stack. Remember: the size of the data array is the capacity of the stack, and the number of elements that are actually in the stack is the count (which is less than or equal to the capacity).
The realloc function is used to resize memory that was previously allocated with malloc or calloc. It takes a pointer to the old memory and the new size, and returns a pointer to the new memory:
void *realloc(void *ptr, size_t size);
int *smol_boi = malloc(10 * sizeof(int));
int *large_boi = realloc(smol_boi, 20 * sizeof(int));