include files:
stdio.h
string.h
ctype.h
genlib.h
simpio.h
strlib.h
The database struct looks like this:
typedef struct{
catT *cats;
int currentMaxSize;
int currentNumberOfCats;
int nextI开发者_如何学God;
} *DBT;
and the "cats" struct looks like this:
typedef struct {
int id;
string name;
char gender;
int birthYear;
int numberOfColours;
string colours[MAX_COLOURS];
} catT;
If we say I got 3 cats in the DBT database and want to erase one of them, how can i code it? I want to have a function to erase a cat!
Well, the size of catT is fixed. Which is good.
If you want to erase the last cat in the list, then it's easy. Just use realloc() so make your DBT smaller. (new size will be 2*sizeof(catT)).
If you want to remove a cat that is not the last cat in the list, then change that. If you don't care about sorting then just override the cat which you want to delete with the last cat in the list (do this using memcpy()). Then you can remove the last cat in the list.
void freeCat(int atIndex, DBT db)
{
if (atIndex < db->currentNumberOfCats)
{
if (atIndex < db->currentNumberOfCats - 1)
{
memmove(db->cats + atIndex,
db->cats + atIndex + 1,
db->currentNumberOfCats - atIndex - 1);
}
db->currentNumberOfCats--;
}
}
But this is expensive. If you are going to repeatedly erase cats, use a linked list or consider allocating catT
on the heap (catT **cats
), so you only have to move the pointers around (don't forget to free
the cat then).
I assume you will allocate memory for 3 cats with *cats
of DBT
.
To erase one of the cats, you need to free the memory for the cat you want to erase.
I can't write the code since I don't know the variables and functions you use but I hope this gives you some idea.
void freeCat(int atIndex, DBT db) { int i;
if (atIndex < db->currentNumberOfCats)
{
if (atIndex < db->currentNumberOfCats - 1)
{
for(i = atIndex; i < db->currentNumberOfCats; i++){
db->cats[i] = db->cats[i+1];
}
}
db->currentNumberOfCats--;
}
}
I did this function and it works perfect! Thanks everyone and @Daniel Gehriger for the start of the function, this helped me very much!
精彩评论