我正在尝试用 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);
最佳答案
当你在结构的末尾声明了一个空数组时,它被称为 flexible array member .您分配它不是通过仅分配数组成员,而是通过分配整个结构。
例如
stack *x = malloc(sizeof *x + sizeof s->items[0] * 32);
上面的 malloc
调用为结构本身分配空间(注意 sizeof *x
的取消引用运算符的使用)加上 32 个元素的数组的空间。
要么是上面的,要么把成员改成指针。
关于c - 如何在 C 中使用 malloc 和 realloc 正确分配结构中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45352625/