2017-10-08 17 views
-2

給定一個帶有幾個元素的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; 
} 
+4

['memmove'(HTTP:/ /en.cppreference.com/w/c/string/byte/memmove)是一個非常好的功能,可以在內存中移動(重疊)數據。 –

+2

另請注意,通過C規範明確提及'fflush'和傳遞僅輸入流(如'stdin')爲[* undefined behavior *](https://en.wikipedia.org/wiki/Undefined_behavior) 。一些標準庫實現已經將它作爲擴展添加,但請儘量避免它。 –

+0

這個問題已經在這裏回答https://stackoverflow.com/questions/15821123/removing-elements-from-an-array-in-c –

回答

0

在您的評論說,你要向下移動剩餘的書籍來看,加:

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

(未測試)

+0

它幾乎奏效。我添加了3本書,然後刪除了第一個元素,第二個元素移動到了第一個元素,但是第三個元素被複制到了第二個元素,因此元素2和3包含相同的值 – Benji

+0

是的,當您刪除元素時,減。 '櫃檯'說有多少元素。 'counter'和更高的任何元素都不存在「,所以它們的值並不重要。 –

+0

好吧,它似乎工作,如果我使用(*計數器) - ; – Benji

相關問題