-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEP9b_stack.c
More file actions
53 lines (44 loc) · 1.01 KB
/
EP9b_stack.c
File metadata and controls
53 lines (44 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "stack.h"
void sNew(stack *s, int elemSize, void (*freefn)(void *))
{
assert(s->elemSize > 0);
s->elemSize = elemSize;
s->logicalLength = 0;
s->allocatedLength = 8;
s->elems = malloc(8 * elemSize);
assert(s->elems != NULL);
}
void sDispose(stack *s)
{
if (s->freefn != NULL)
{
for(int i = 0; i < s->logicalLength; i++)
{
s->freefn((char *)s->elems + i * s->elemSize);
}
}
free(s->elems);
}
void sPush(stack *s, void *elemAddress)
{
if(s->logicalLength == s->allocatedLength)
sGrow(s);
void *target = (char*)s->elems + s->logicalLength * s->elemSize;
memcpy(target, elemAddress, s->elemSize);
s->logicalLength++;
}
void sPop(stack *s, void *elemAddress)
{
s->logicalLength--;
void *source = (char*)s->elems + s->logicalLength * s->elemSize;
memcpy(elemAddress, source, s->elemSize);
}
static void sGrow(stack *s)
{
s->allocatedLength *= 2;
s->elems = realloc(s->elems, s->allocatedLength * s->elemSize);
}