我有一个结构:
typedef struct score_entry
{
char name[21];
int score;
} score_entry;
和一个数组:
score_entry readin[1000];
我想编写一个使用 score_entry 数组
和 name(String)
的函数,并删除数组中具有该名称的所有结构并返回新数组。这可能吗?如果是这样怎么办?
最佳答案
好吧,你不能从 C 中的数组中“删除”元素。但是你可以计算与 name 不匹配的元素,在堆上创建一个新数组,然后复制兴趣。基本代码可能如下所示,但是,您应该确保其安全,不要对结构标记和类型名使用相同的标识符,并返回新数组的大小。
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;
}
关于c - 从结构数组中删除;s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9895955/