Dynamic Array of Void Pointers
arrays, c, pointers, void-pointers
Solution
First, I think what you intend to have in your structure is an array of generic pointers (array of `void *`), because your items are `void *`, and you want to store them as an array. That is, you want a dynamic array of `void *`, thus, you should use `void **`:
struct SET {
void **data;
int elements;
int allocated;
};
Of course, your `add` function needs to be updated:
struct SET add(struct SET s, void *item) {
if (is_element_of(item, s) == 0) {
if (s.elements == s.allocated) {
s.allocated = 1 + (s.allocated * 2);
void **temp = realloc(s.data, (s.allocated * sizeof(*s.data)));
if (!temp) {
fprintf(stderr, "ERROR: Couldn't realloc memory!\n");
return s;
}
s.data = temp;
}
s.data[s.elements] = item;
s.elements = s.elements + 1;
puts("Item added to set\n");
return s;
}
else {
fprintf(stdout, "Element is already in set, not added\n");
return s;
}
}
Note the `realloc` line was changed: you don't want to realloc to `s.allocated * sizeof(s)`, you want `s.allocated*sizeof(*s.data)`, since you'll be storing elements of type `void *` (the type of `*s.data` is `void *`, I didn't explicitly write `void *` to make it easier to accomodate possible future changes).
Also, I believe you should change your functions to receive and return pointers to `struct SET`, otherwise, you will always be copying around the structure (remember that values are passed by copy).
Problem
I'm trying to create a dynamic set abstract data type, based on a dynamic array. However, I get a compiler warning and an error when I try to add the data to the array, which are: warning: dereferencing 'void *' pointer [enabled by default] error: invalid use of void expression My code is as follows, I've marked the problematic line with a comment ``` struct SET { //general dynamic array void *data; int elements; //number of elements int allocated; // size of array }; struct SET create() { //create a new empty set struct SET s; s.data = NULL; s.elements = 0; s.allocated = 0; //allocations will be made when items are added to the set puts("Set created\n"); return s; } struct SET add(struct SET s, void *item) { //add item to set s if(is_element_of(item, s) == 0) //only do this if element is not in set { if(s.elements == s.allocated) //check whether the array needs to be expanded { s.allocated = 1 + (s.allocated * 2); //if out of space, double allocations void *temp = realloc(s.data, (s.allocated * sizeof(s))); //reallocate memory according to size of the set if(!temp) //if temp is null { fprintf(stderr, "ERROR: Couldn't realloc memory!\n"); return s; } s.data = temp; } s.data[s.elements] = item; //the error is here s.elements = s.elements + 1; puts("Item added to set\n"); return s; } else { fprintf(stdout, "Element is already in set, not added\n"); return s; } } ``` I've done research on void pointers, but clearly I'm missing something here. I'd appreciate any help I can get. Thanks for reading and hopefully answering!