Question

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.

Was it helpful?

Solution

Here:

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

you are redeclaring src (in a block scope), you want:

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.

OTHER TIPS

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* 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 ***
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top