1

I need to write a simple library program using the structure 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; 

When the program runs the user can take out books from the library/add books/print books etc:

#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; } 

I need some way to store the books so I can change the library as the program runs(I don't know in advance how many books the user will add/remove during the program run).

I don't want to use dynamic memory, can I define an empty array of books this way: Book books[BOOK_NUM] = { 0 }; ? It seems to work but 0 is an int type and not a Book type, will I run into troubles?

6
  • Is there any reason as to why you want to avoid dynamically allocating memory? Commented May 27, 2018 at 11:11
  • books[BOOK_NUM] = { 0 } just initializes elements to zero, I don't understand what dynamic memory has to do with that? Commented May 27, 2018 at 11:14
  • Book books[BOOK_NUM] = { 0 }; I think it's ok or use loop or make it global. Commented May 27, 2018 at 11:16
  • or use memeset(). Commented May 27, 2018 at 11:21
  • Always a bug: not testing the return value from scanf. Commented May 27, 2018 at 12:05

2 Answers 2

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

when you initialize a struct variable with initializer { }, all of its other members will be initialized to default value & since in your case struct book declaration is global, all members of structure will automatically initialized to 0 for int & floating point,'\0' for char and NULL for pointer variable.

Or you can use memset() like

memset(&books, 0, sizeof(books)); 
Sign up to request clarification or add additional context in comments.

2 Comments

@Venuce no, don't. If you have a new question, ask a new question. Don't try to change history, that's just confusing.
struct book is type. books[BOOK_NUM] declared in main it is not global. Zero is just default state of memory.
0
books[BOOK_NUM] = { 0 }; // copiler gives warning 

Proper way to do this is:

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

Comments