給定一個帶有幾個元素的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'(HTTP:/ /en.cppreference.com/w/c/string/byte/memmove)是一個非常好的功能,可以在內存中移動(重疊)數據。 –
另請注意,通過C規範明確提及'fflush'和傳遞僅輸入流(如'stdin')爲[* undefined behavior *](https://en.wikipedia.org/wiki/Undefined_behavior) 。一些標準庫實現已經將它作爲擴展添加,但請儘量避免它。 –
這個問題已經在這裏回答https://stackoverflow.com/questions/15821123/removing-elements-from-an-array-in-c –