-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;
}
6
  • 4
    memmove is a very good function to move (overlapping) data around in memory. Commented Oct 8, 2017 at 16:44
  • 2
    Also note that falling fflush and passing an input-only stream (like stdin) is explicitly mentioned as undefined behavior by the C specification. Some standard library implementations have added it as an extension, but please try to avoid it. Commented Oct 8, 2017 at 16:45
  • this question is already answered here stackoverflow.com/questions/15821123/… Commented Oct 8, 2017 at 16:48
  • I only used fflush because the add_book function didnt work without it Commented Oct 8, 2017 at 16:49
  • 1
    @Benji That's because you're using scanf wrong. Commented Oct 8, 2017 at 16:51

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

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
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.
Ok it seems to work, if I use (*counter)--;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.