我想創建一個基於動態數組的動態集合抽象數據類型。不過,我得到一個編譯器警告和錯誤,當我嘗試添加的數據陣列,它們是:虛空指針的動態數組
警告:提領「無效*」指針[默認啓用]
錯誤:無效使用無效的表達
我的代碼如下,我已加評論
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;
}
}
我已經做了研究空指針問題的行,但很明顯,我在這裏失去了一些東西。我會很感激我能得到的任何幫助。感謝閱讀並希望回答!
你應該把所有的函數定義在這裏..它似乎是成員數據應該是無效的**? – michaeltang
爲什麼會這樣? –