【发布时间】:2017-07-27 13:43:49
【问题描述】:
我正在尝试在 C 中实现堆栈,同时也在尝试学习 C。我的背景主要是高级语言(如 Python),所以很多内存分配对我来说都是新的。
我有一个程序按预期运行,但发出警告,让我相信我做错了什么。
代码如下:
typedef struct {
int num_items;
int top;
int items[];
} stack;
void push(stack *st, int n) {
st->num_items++;
int* tmp = realloc(st->items, (st->num_items) * sizeof(int));
if (tmp) {
*(st->items) = tmp;
}
st->items[st->num_items - 1] = n;
st->top = n;
}
int main() {
stack *x = malloc(sizeof(x));
x->num_items = 0;
x->top = 0;
*(x->items) = malloc(0);
push(x, 2);
push(x, 3);
printf("Stack top: %d, length: %d.\n", x->top, x->num_items);
for (int i = 0; i < x->num_items; i++) {
free(&(x->items[i]));
}
free(x->items);
free(x);
}
这是输出:
Stack top: 3, length: 2.
这是预期的。但是在编译过程中,出现以下错误:
> gcc -x c -o driver driver.c
driver.c: In function 'push':
driver.c:16:16: warning: assignment makes integer from pointer without a cast
*(st->items) = tmp;
...
driver.c: In function 'main':
driver.c:27:14: warning: assignment makes integer from pointer without a cast
*(x->items) = malloc(0);
【问题讨论】:
标签: c arrays pointers memory struct