Dynamic Array in C - Hacker Rank Solution
Dynamic arrays in C are represented by pointers with allocated memory they point on. You can use either or functions from
When a new book is added, you should increment the corresponding value from array . However, it's not that easy for . You should create a new array of the size , then copy all previous values to this new array and then append to the end of it. After all this, you should free the previously allocated memory using function and then reassign to this new array.
#include
ReplyDelete#include
/*
* This stores the total number of books in each shelf.
*/
int* total_number_of_books;
/*
* This stores the total number of pages in each book of each shelf.
* The rows represent the shelves and the columns represent the books.
*/
int** total_number_of_pages;
int main()
{
int total_number_of_shelves;
scanf("%d", &total_number_of_shelves);
int total_number_of_queries;
scanf("%d", &total_number_of_queries);
total_number_of_books = calloc(total_number_of_shelves, sizeof(int));
total_number_of_pages = malloc(total_number_of_shelves * sizeof(int *));
for (int i = 0; i < total_number_of_shelves; i++) {
total_number_of_pages[i] = calloc(1100, sizeof(int));}
while (total_number_of_queries--) {
int type_of_query;
scanf("%d", &type_of_query);
if (type_of_query == 1) {
/* the query of first type here */
int x, y;
scanf("%d %d", &x, &y);
*(total_number_of_books+x)+=1;
*(total_number_of_pages+x)=realloc(*(total_number_of_pages+x), *(total_number_of_books+x)*sizeof(int));
*(*(total_number_of_pages+x)+*(total_number_of_books+x)-1)=y;
} else if (type_of_query == 2) {
int x, y;
scanf("%d %d", &x, &y);
printf("%d\n", *(*(total_number_of_pages + x) + y));
} else {
int x;
scanf("%d", &x);
printf("%d\n", *(total_number_of_books + x));
}
}
if (total_number_of_books) {
free(total_number_of_books);
}
for (int i = 0; i < total_number_of_shelves; i++) {
if (*(total_number_of_pages + i)) {
free(*(total_number_of_pages + i));
}
}
if (total_number_of_pages) {
free(total_number_of_pages);
}
return 0;
}
Dynamic Array in C – Hacker Rank Solution
ReplyDeletehttps://www.codeworld19.com/dynamic-array-in-c-hacker-rank-solution/