Reputation: 903
I have a structure:
typedef struct score_entry
{
char name[21];
int score;
} score_entry;
and an array:
score_entry readin[1000];
I want to write a function that consumes a score_entry array
and a name(String)
and remove all structures in the array with that name and return the new array. Is this possible? if so how could it be done ?
Upvotes: 0
Views: 7208
Reputation: 11162
How do you keep track of the number of elements in the array? Although you can't delete elements; you can squish them out, then decrement the count, for example:
void
delete(score arr[], int *nelem, score target){
int hi, lo, count;
for(hi=lo=0; hi<*nelem; hi++){
arr[lo] = arr[hi];
if(!same(target, arr[lo]))
lo++;
}
*nelem = lo;
}
Upvotes: 0
Reputation: 8180
Well you can't "remove" elements from an array in C. But you can count the elements that does not match name, create a new array on the heap, and copy all elements of interest. The basic code could look like this, however, you should make it safe, don't use the same identifier for the struct tag and typename, and return the size of the new array.
score_entry *sortout(score_entry *array, char* string) {
score_entry *newarray;
int i, n=0;
/* measure the size of the filtered array copy */
for(i=0; i<1000; i++) {
if (strcmp(array[i].name, string) n++;
}
/* allocate space for the filtered copy */
newarray = (score_entry*)calloc(n, sizeof(score_entry));
/* filter and copy the data */
for(i=0, n=0 ; i<1000; i++) {
if (strcmp(array[i].name, string))
newarray[n++] = array[i];
}
return newarray;
}
Upvotes: 2
Reputation: 28535
Array elements cannot be removed once created. Instead of
score_entry readin[1000];
Consider creating a linked list. First add a new element to the structure
typedef struct score_entry
{
char name[21];
int score;
struct score_entry *next;
}
And then look into any example of creating singly linked lists and then proceed to your new function implementation wherein you can easily delete nodes which match a criteria
Upvotes: 0
Reputation: 36487
I'd probably just use a linked list and then delete elements in question. Otherwise you'd have to iterate over your array and skip/move entries not matching your search string/name.
Upvotes: 0