c - 从结构数组中删除;s

标签 c arrays string structure

我有一个结构:

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/

相关文章:

c - 指针和字符数组

c - Linux 上 C 中的 GTK+ 3.0 : handle multiple calls of callback function by signals

python - 使用一维 bool 数组过滤二维数组

ruby - 接受字符串的方法

python - 检查一个字符串是否包含一个在列表 python 中的字符串

C 指针程序使用指针交换字符串

php - 将带连接的 Mysql select 语句转换为多维数组

php - 此后如何使用 explode ,因为在我的数据库列中,所有值都在产品列中可用,如下所示

基于输入的Python分区字符串

c - 管道输入到 stdin 在 c 中不起作用