【问题标题】:Reallocating array inside struct在结构内重新分配数组
【发布时间】:2014-05-31 01:21:05
【问题描述】:
typedef struct {
    int count;
    int *items;
}set;

set* set_alloc(set *src, int num);
int set_insert(set *s, int num);

int main() {
    set *A = NULL;
    A = set_alloc(A, 0);
    A = set_alloc(A, 1); //this and line below is part of inserting function
    A->items[0] = 2;
    system("pause");
}   

set* set_alloc(set *src, int num) {
    if (src == NULL && num == 0) {
            set *src = (set*)malloc(sizeof(set));
        src->count = 0;
        src->items = NULL;
    }
    else {
        src->count = num;
        src->items = (int*)realloc(src->items, num*sizeof(int));
    }
    return src;
}

上面的代码能够为集合内的项目数组和集合本身分配内存,但是,它无法重新分配该项目数组。我可以将它设置为恒定大小,但我真的没有想解决这个问题,因为我在以前的项目中遇到过。

【问题讨论】:

  • 目前尚不清楚realloc 'fails' 在这里是如何发生的。请准确描述正在发生的事情。
  • 另外,请注意不要将realloc 的结果分配回您要重新分配的指针。如果realloc 失败并返回NULL 怎么办?然后你失去了原来的指针,就会有内存泄漏。
  • @Poody:你不是 malloc-ing 一个局部变量 'set *src',而不是实际的输入参数 'src'??
  • @raj raj:我现在看到了,在下面的答案中。我来回切换代码。解决了,但我还是很困惑

标签: c arrays allocation realloc


【解决方案1】:

这里:

set *src = (set*)malloc(sizeof(set));

你正在重新声明src(在块范围内),你想要:

src = malloc(sizeof(set));

我可以将其设置为恒定大小,但我真的不想四处走动 这个问题是因为我在以前的项目中遇到过。

当您事先不知道大小时,realloc 的替代方法是链表。

【讨论】:

    【解决方案2】:

    您的函数永远不会从函数 set_alloc 返回新分配的“*src”,请参阅下面的我的 cmets,请使用相同的 *src 进行分配,您的代码应该可以工作。

        set* set_alloc(set *src, int num) {
        if (src == NULL && num == 0) {
            set *src = (set*)malloc(sizeof(set));  ***//<--- This pointer is local to if block.***
     *//Please Correct code as =>*            src = (set*)malloc(sizeof(set));
    
            src->count = 0;
            src->items = NULL;
        }
        else {
            src->count = num;
            src->items = (int*)realloc(src->items, num*sizeof(int));
        }
        return src;   ***// <-- This is returning the in parameter not the malloced pointer ***
    }
    

    【讨论】:

    • 是的。该函数最初创建了一个新集,分配内存并返回它,但我错误地升级了它,以便它也可以重新分配。谢谢
    猜你喜欢
    • 2019-02-02
    • 2011-09-04
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多