Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement stack in c

Tags:

c

malloc

I want to make stack which work with dynamic memory allocation, but I need to know about which it is more efficient :
to have an initial size like 10 for example , and then I double it if I need more.
or I can have an initial size = 1 and for every new input adding one place . !?!

int *tmp = malloc(sizeof(int) * 2 * dm->capacity); \* dm->capacity = 10 *\
int *tmp = malloc(sizeof(int));
like image 754
Rawhi Avatar asked Jan 17 '23 14:01

Rawhi


1 Answers

Doubling when needed is way more efficient.

If you allocate a new array for every push operation, then you do an amount of work proportional to the square of the number of stack elements (when you push element N+1, you must copy the previous N elements to the new array).

If you double the array when needed, then the number of copies you do is proportional to the logarithm of N, and for any nontrivial size stack, that's substantially smaller, as you know.

like image 75
Ernest Friedman-Hill Avatar answered Jan 27 '23 19:01

Ernest Friedman-Hill