【问题标题】:How do I shift elements down in an array of string of struct? [duplicate]如何在结构字符串数组中向下移动元素? [复制]
【发布时间】:2018-03-19 21:33:52
【问题描述】:

给定一个包含多个元素的 struct 数组,我想删除元素 2,并希望元素 3、4、5.. 转移到 2、3、4。

在我下面的代码中,添加和删除功能可以正常工作。我尝试过使用 strcpy() 函数,但它没有用。

    struct Books {
        char title[20];
        char author[20];
    };

void add_book(struct Books book1[], int *counter){

    fflush(stdin);
    printf("Title: ");
    gets(book1[*counter].title);
    printf("Author: ");
    gets(book1[*counter].author);
    *counter++;

    return;
}

void delete_book(struct Books book1[], int *counter){

    int i = 0;
    int delete = 0;
    printf("What nr of book you want to delete: ");
    scanf("%d", &delete);

    book1[delete-1].title[0] = '\0';
    book1[delete-1].author[0] = '\0';
    *counter--;

    /*
     here I want to move elements down one step if I delete for example one 
     element in the middle
    */
    return;
}

int main(){

    struct Books book1[50];
    int count = 0; //for keeping track of how many books in the register

    add_book(book1, &count);
    delete_book(book1, &count);

    return 0;
}

【问题讨论】:

  • memmove 是一个非常好的函数,可以在内存中移动(重叠)数据。
  • 另请注意,下降fflush 并传递一个仅输入流(如stdin)在C 规范中明确提到为undefined behavior。一些标准库实现已将其添加为扩展,但请尽量避免。
  • 这个问题已经在这里回答了stackoverflow.com/questions/15821123/…
  • 我只使用了 fflush,因为没有它 add_book 函数就无法工作
  • @Benji 那是因为你用错了scanf

标签: c arrays function struct


【解决方案1】:

在您的 cmets 说您要向下移动剩余书籍时,添加:

    memmove(&book1[delete-1],  &book1[delete], (*counter-delete)*sizeof(struct Books);
    *counter--;  // better to decrement it here

(未测试)

【讨论】:

  • 几乎成功了。我添加了 3 本书,然后删除了第一个元素,第二个元素移动到了第一个元素,但第三个元素被复制到了第二个元素,因此元素 2 和 3 包含相同的值
  • 是的,当你删除一个元素时,就会少一个。 counter 表示有多少元素。 counter 和更高级别的任何元素“不存在”,因此它们的值并不重要。
  • 好的,如果我使用 (*counter)--;
猜你喜欢
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 2016-11-12
  • 2013-01-29
  • 1970-01-01
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多