-2

Given an array of a struct with several elements, I would like to delete, say element 2, and want the elements 3,4,5.. to shift to 2,3,4.

In my code below, the add and delete functions work fine. I have tried with strcpy() function but it didn't work.

    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;
}
Bei
  • 95
  • 1
  • 1
  • 9
  • 4
    [`memmove`](http://en.cppreference.com/w/c/string/byte/memmove) is a very good function to move (overlapping) data around in memory. – Some programmer dude Oct 08 '17 at 16:44
  • 2
    Also note that falling `fflush` and passing an input-only stream (like `stdin`) is explicitly mentioned as [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior) by the C specification. Some standard library implementations have added it as an extension, but please try to avoid it. – Some programmer dude Oct 08 '17 at 16:45
  • this question is already answered here https://stackoverflow.com/questions/15821123/removing-elements-from-an-array-in-c – Ahmed Masud Oct 08 '17 at 16:48
  • I only used fflush because the add_book function didnt work without it – Bei Oct 08 '17 at 16:49
  • 1
    @Benji That's because you're using `scanf` wrong. – melpomene Oct 08 '17 at 16:51
  • how do I use it and how should I use it? – Bei Oct 08 '17 at 17:04

1 Answers1

0

At the point where your comments says you want to move the remaining books down, add:

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

(Not tested)

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • It almost worked. I added 3 books, and then deleted the first element, the second element moved to the first element, but the third was copied to the second so element 2 and 3 contained same value – Bei Oct 08 '17 at 17:19
  • Yes, and when you delete an element, there is one less. `counter` says how many elements there are. Any element from `counter` and higher "does not exist" so their values are not important. – Paul Ogilvie Oct 08 '17 at 17:21
  • Ok it seems to work, if I use (*counter)--; – Bei Oct 08 '17 at 17:56