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 = 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.