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!