给定一个带有多个元素的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;
}
答案 0 :(得分:0)
如果您的评论显示您想要移动剩余的图书,请添加:
memmove(&book1[delete-1], &book1[delete], (*counter-delete)*sizeof(struct Books);
*counter--; // better to decrement it here
(未经测试)