【发布时间】:2014-08-15 04:58:34
【问题描述】:
我有一个用来表示通用堆栈的数组。
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;
}
这是在保留数据的同时将数组加倍的正确方法吗?
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);
}
但是,当我尝试像这样从 push_stack() 调用它时:
void push_stack (Stack *s, void *data) {
if (full_stack(s)) realloc_stack(s);
s->data[s->size++] = data;
}
我遇到了这个问题:基本上是一堆零,实际数字应该是。
int main() {
Stack *intStack = new_stack(sizeof(int));
for (int i = 0; i < 15; ++i) {
push_stack(intStack, (void*)i);
}
}
结果:
Printing stack:
14
13
12
11
10
0
0
0
0
9
8
7
6
1
0
【问题讨论】:
-
Stack.data的类型是什么?请记住,s->data + old_capacity将基于该大小,而不是sizeof(char)。您在这里冒着缓冲区溢出的风险。 -
tmp->data = calloc(tmp->capacity, type);s->data = realloc(s->data, s->capacity);: 这在容量的意义上是不一致的。 -
@Raymond 你有一个结构类型
Stack,你没有显示。它有一个data成员,我们看不到它的类型和大小。 -
s->data[s->size++] = data;:type和大小没有一致性。 -
所以应该是:s->data = realloc(s->data, s->type * s->capacity);对吗?
标签: c arrays dynamic stack realloc