Grow the backing array
Updated
When size == capacity, push must allocate a larger array, copy the occupied prefix, then write the new top. Doubling is the usual growth so push stays amortized O(1).
What to focus on
Copy only 0..size-1, not garbage past the top. Empty growth is allocating the first capacity. Shrinking is optional.
Worked examples
full
a = [4, 1, 9], cap 3, push 8- alloc cap 6
- copy 4,1,9
- write 8
Result: [4, 1, 9, 8]
not full
a = [4, 1, 9, _, _], cap 5, size 3, push 8- no copy
- write at index 3
Result: [4, 1, 9, 8]
empty first grow
a = [], cap 0, push 4- alloc cap 1 or 8
- write 4
Result: [4]
Try it
Write growPush(a, x). a is the array-backed stack. x is the integer to push. size is occupied length. capacity is allocated length. If size equals capacity, allocate a larger array, copy 0..size-1, then write x. If not full, do not copy. Push onto full [4, 1, 9] copies 3 then writes 8. Size-3 cap-5 copies 0. Empty cap-0 allocates.
Values are integers. You may grow from cap 0. When not full, do not copy.