gpt4 book ai didi

c - 如何在结构字符串数组中向下移动元素?

转载 作者:行者123 更新时间:2023-11-30 20:32:57 25 4
gpt4 key购买 nike

给定一个 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(&book1[delete-1],  &book1[delete], (*counter-delete)*sizeof(struct Books);
*counter--; // better to decrement it here

(未测试)

关于c - 如何在结构字符串数组中向下移动元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46633495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com