简体   繁体   English

在struct中重新分配数组

[英]Reallocating array inside struct

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;
}

Code above is able to allocate memory for the array of items inside the set and for the set itself, however, it fails to realloc that array of items.. I could set it a constant size, but I don't really wanna go around this problem because I've had it in previous projects. 上面的代码能够为集合内部的项目数组和集合本身分配内存,但是,它无法重新分配该项目数组..我可以将它设置为常量,但我真的不想四处走动这个问题,因为我在之前的项目中已经有了它。

Here: 这里:

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

you are redeclaring src (in a block scope), you want: 你要重新声明src (在块范围内),你想要:

src = malloc(sizeof(set));

I could set it a constant size, but I don't really wanna go around this problem because I've had it in previous projects. 我可以设置一个恒定的大小,但我真的不想解决这个问题,因为我已经在之前的项目中使用过它。

An alternative to realloc when you don't know the size beforehand is a linked list. 当您事先不知道大小时, realloc的替代方法是链接列表。

Your function never returns the newly allocated "*src" from function set_alloc, see my comments below, please use the same *src for allocation, and your code should work. 你的函数永远不会从函数set_alloc返回新分配的“* src”,请参阅下面的评论,请使用相同的* 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 ***
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM