2014-11-17 111 views
1

我有一個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

你得到一個錯誤,因爲你沒有爲'b'分配內存,因爲你將它定義爲一個指向'struct bst'的指針 –

+0

當malloc失敗時,max的值是多少? –

+0

'struct bst * b;' - >'struct bst * b = malloc(sizeof(* b));' – BLUEPIXY

回答

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。除非你確切地知道你在做什麼,否則千萬不要混合和匹配intfloat邏輯。