2014-11-17 114 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逻辑。