Last active
October 29, 2023 19:23
-
-
Save Farzinkh/4e2b0f5bd671d80e628cade51b387102 to your computer and use it in GitHub Desktop.
Struct example for query on books and readers in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct Book { | |
char *name; | |
int total_reads; | |
} Book; | |
typedef struct Reader { | |
char *username; | |
Book *read_books; | |
int read_books_size; | |
} Reader; | |
int count_reads(Reader **readers, int readers_size, char *book_name) | |
{ | |
printf("\nlooking for %s\n",book_name); | |
int count=0; | |
for(int i=0; i<readers_size; i++){ | |
for(int j=0; j< readers[i]->read_books_size; j++){ | |
Book *book = readers[i]->read_books; | |
printf("%s: %s\n",readers[i]->username,book[j].name); | |
if(book[j].name == book_name){ | |
count++; | |
} | |
} | |
} | |
return count; | |
} | |
int main() | |
{ | |
Book books[] = { {.name = "Science Fiction", .total_reads = 300}, | |
{.name = "Mystery", .total_reads = 150}, | |
{.name = "Fantasy", .total_reads = 200} }; | |
Reader reader1 = {.username = "Alice", .read_books = books, .read_books_size = 3}; | |
Reader reader2 = {.username = "Bob", .read_books = &books[1], .read_books_size = 1}; | |
Reader reader3 = {.username = "Eve", .read_books = &books[2], .read_books_size = 1}; | |
Reader *readers[] = {&reader1, &reader2, &reader3}; | |
printf("%d\n", count_reads(readers, 3, "Mystery")); | |
printf("%d\n", count_reads(readers, 3, "Science Fiction")); | |
printf("%d\n", count_reads(readers, 3, "Fantasy")); | |
reader3.username="Emili"; | |
printf("%d\n", count_reads(readers, 3, "Horror")); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment