【发布时间】:2014-01-27 22:56:18
【问题描述】:
我正在尝试基于动态数组创建动态集合抽象数据类型。但是,当我尝试将数据添加到数组时,会收到编译器警告和错误,它们是:
警告:取消引用 'void *' 指针 [默认启用]
错误:无效表达式的使用无效
我的代码如下,有问题的行我已经标注了注释
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;
}
}
我对 void 指针进行了研究,但显然我在这里遗漏了一些东西。我会很感激我能得到的任何帮助。感谢阅读并希望回答!
【问题讨论】:
-
你应该把所有的函数定义都放在这里..似乎成员数据应该是无效的**?
标签: c arrays pointers void-pointers