在C中初始化用户定义的类型数组

时间:2018-05-27 11:04:36

标签: c

我需要使用结构Book:

编写一个简单的库程序
typedef struct book {
    char name[NAME_LENGTH];
    char author[AUTHOR_NAME_LENGTH];
    char publisher[PUBLISHER_NAME_LENGTH];
    char genre[GENRE_LENGTH];
    int year;
    int num_pages;
    int copies;
} Book;

当程序运行时,用户可以从库中取出书籍/添加书籍/印刷书籍等:

#define BOOK_NUM        50

int main(){

Book books[BOOK_NUM] = { 0 };
int opt = 0, books_counter = 0, *books_counter_p;
books_counter_p = &books_counter;


do {
    print_menu();
    scanf("%d", &opt);
    while (opt < 1 || opt > 5) {
        printf("Invalid option was chosen!!!\n");
        print_menu();
        scanf("%d", &opt);
    }

    switch (opt) {
        case 1:
            // Add book to library
            add_book(books, books_counter_p);


            break;
        case 2:
            // Take a book from library
            break;
        case 3:
            // Return book
            break;
        case 4:
            // Print all books
            break;
        case 5:
            // Release all memory allocated for library
            break;
        default:
            printf("We should not get here!\n");
    }
} while (opt != 5);

return 0;
}

我需要一些方法来存储书籍,以便我可以在程序运行时更改库(我不知道用户将在程序运行期间添加/删除多少本书)。

我不想使用动态内存,我可以这样定义一个空的书籍数组:书籍[BOOK_NUM] = {0}; ? 它似乎工作但是0是一个int类型而不是Book类型,我会遇到麻烦吗?

2 个答案:

答案 0 :(得分:1)

Book books[BOOK_NUM] = { 0 } /* creating & initializing array of structure variable */

使用初始化程序{ }初始化struct变量时,其所有其他成员将初始化为默认值&amp;因为在您的情况下struct book声明是全球,所有结构成员都会自动初始化为0 int&amp; floating point'\0' charNULL指针变量。

或者您可以使用memset()之类的

memset(&books, 0, sizeof(books));

答案 1 :(得分:0)

books[BOOK_NUM] = { 0 }; // copiler gives warning

正确的方法是:

books[BOOK_NUM] = {{0}}; //set the first field of the first struct to 0 and all the rest to 0 implicitly