We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Stack Push

Ok, so let's actually store some data instead of just allocating memory for no practical purpose (a.k.a "haskell programming").

Making Room

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, -, -, -]

Assignment

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).

Tip

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));