我有BST结构:
struct bst {
int *data;
int max;
};
我最初有一个创建bst的功能:
struct bst *create_bst(int max) {
struct bst *b;
b->data = malloc(pow(2, max) * sizeof(int));
return b;
}
但是我在为数据分配内存的行中遇到了错误 我做错了吗?
答案 0 :(得分:3)
您没有为struct
本身分配数据,只是其中一个成员。这应该有所帮助:
struct bst *create_bst(int max) {
struct bst *b;
if ((b = calloc((size_t)1, sizeof(struct bst))) == NULL) {
printf("Allocation error\n");
return NULL;
}
if ((b->data = calloc((size_t)1<<max, sizeof(int))) == NULL) {
printf("Allocation error\n");
free(b);
return NULL;
}
return b;
}
稍后在代码的其他部分中,您需要清理此内存。即:free(b->data); free(b)
。
此外,remember that pow
doesn't work quite how you think it does。您可以获得类似pow(5,2) == 24.999999...
的内容,当您将此值分配给整数变量时,它会被截断为24
。除非您确切知道自己在做什么,否则永远不要混淆和匹配int
和float
逻辑。