I have an array used to represent a generic stack.
struct Stack {
int size;
int type;
int capacity;
void **data; // An array of generic data.
};
Stack *new_stack(int type) {
Stack *tmp = malloc(sizeof(Stack));
assert(tmp != NULL);
tmp->size = 0;
tmp->type = type;
tmp->capacity = DEFAULT_CAPACITY;
tmp->data = calloc(tmp->capacity, type);
assert(tmp->data != NULL);
return tmp;
}
Would this be the proper way to double the array while preserving its data?
void realloc_stack(Stack *s) {
int old_capacity = s->capacity;
s->capacity *= 2;
s->data = realloc(s->data, s->capacity);
memset(s->data + old_capacity, 0, old_capacity);
assert(s->data != NULL);
}
However, when I try calling this from push_stack() like this:
void push_stack (Stack *s, void *data) {
if (full_stack(s)) realloc_stack(s);
s->data[s->size++] = data;
}
I get this problem: basically a bunch of zeroes where the actual numbers should be.
int main() {
Stack *intStack = new_stack(sizeof(int));
for (int i = 0; i < 15; ++i) {
push_stack(intStack, (void*)i);
}
}
Results:
Printing stack:
14
13
12
11
10
0
0
0
0
9
8
7
6
1
0