【问题标题】:Allocating dynamic array within a function of a structure在结构的函数内分配动态数组
【发布时间】:2014-11-17 13:29:33
【问题描述】:

我有一个 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;
}

但我在为数据分配内存的那一行出现错误。
我做错了吗?

【问题讨论】:

  • 您收到一个错误,因为您没有为b 分配内存,因为您将它定义为指向struct bst 的指针
  • malloc失败时max的值是多少?
  • struct bst *b; --> struct bst *b = malloc(sizeof(*b));
  • @T.V.我只是添加 b = malloc(sizeof(struct bst)); ?
  • @T.V.你误解了*b*b 不是指针。

标签: c arrays memory struct


【解决方案1】:

您没有为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-&gt;data); free(b).

另外,remember that pow doesn't work quite how you think it does。你可以得到类似pow(5,2) == 24.999999... 的东西,当你把这个值赋给一个整数变量时,它会被截断为24。除非您确切知道自己在做什么,否则切勿混用 intfloat 逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2019-07-19
    相关资源
    最近更新 更多