HackerRank C- Dynamic Array in C




Snow Howler has got an assistant, Oshie, provided by the Department of Education. Although inexperienced, Oshie can handle all of the queries of types 2 and 3.

Help Snow Howler deal with all the queries of type 1.

Oshie has used two arrays:



  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. /*
  4. * This stores the total number of books in each shelf.
  5. */
  6. int* total_number_of_books;
  7. /*
  8. * This stores the total number of pages in each book of each shelf.
  9. * The rows represent the shelves and the columns represent the books.
  10. */
  11. int** total_number_of_pages;
  12. int main()
  13. {
  14. int total_number_of_shelves;
  15. scanf("%d", &total_number_of_shelves);
  16. int total_number_of_queries;
  17. scanf("%d", &total_number_of_queries);
  18. total_number_of_books=(int*)malloc(sizeof(int)*total_number_of_shelves);
  19. total_number_of_pages=(int**)malloc(sizeof(int*)*total_number_of_shelves);
  20. for(int i=0; i<total_number_of_shelves; i++){
  21. total_number_of_books[i]=0;
  22. total_number_of_pages[i]=(int*)malloc(sizeof(int));
  23. }
  24. while (total_number_of_queries--) {
  25. int type_of_query;
  26. scanf("%d", &type_of_query);
  27. if (type_of_query == 1) {
  28. int x, y;
  29. scanf("%d %d", &x, &y);
  30. *(total_number_of_books+x)+=1;
  31. *(total_number_of_pages+x)=realloc(*(total_number_of_pages+x), *(total_number_of_books+x)*sizeof(int));
  32. *(*(total_number_of_pages+x)+*(total_number_of_books+x)-1)=y;
  33. } else if (type_of_query == 2) {
  34. int x, y;
  35. scanf("%d %d", &x, &y);
  36. printf("%d\n", *(*(total_number_of_pages + x) + y));
  37. } else {
  38. int x;
  39. scanf("%d", &x);
  40. printf("%d\n", *(total_number_of_books + x));
  41. }
  42. }
  43. if (total_number_of_books) {
  44. free(total_number_of_books);
  45. }
  46. for (int i = 0; i < total_number_of_shelves; i++) {
  47. if (*(total_number_of_pages + i)) {
  48. free(*(total_number_of_pages + i));
  49. }
  50. }
  51. if (total_number_of_pages) {
  52. free(total_number_of_pages);
  53. }
  54. return 0;
  55. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube