[英]Allocating dynamic array within a function of a structure
我有一個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;
}
但是我在為數據分配內存的行中遇到錯誤。
難道我做錯了什么?
您沒有為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)
free(b->data); free(b)
。
此外, 請記住, pow
並不像你認為的那樣 。 你可以得到類似pow(5,2) == 24.999999...
,當你將這個值賦給一個整數變量時,它會被截斷為24
。 除非你確切知道你在做什么,否則永遠不要混合和匹配int
和float
邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.