In: Computer Science
2. [9 pts] Write the code necessary to properly allocate memory (on the heap) in the following scenarios
a). An array a of n characters
b) An array b of m+n integers
c) An x × y × z matrix m1 of integers initialized to 0s
Use C code
#include<stdio.h>
#include<stdlib.h>
void main()
{
   // malloc() is used to allocate memory at runtime and
memory at runtime is allocated using heap
   int count;
   printf("Enter count of characters for which mmeory is
required: ");
   scanf("%d", &count);
  
   if(count <= 0)
   {
       printf("Size should be more than 0,
always!!");
       return;
   }
  
   // This is the syntax for malloc() function: (void
*)malloc(number_of_bytes)
   /*
   Since malloc() returns a void pointer, we need to cast
it into some predefined data type.
   */
   // part a
   char *a = (char *)malloc(sizeof(char)*count);
  
printf("\n--------------------------------------\n");
   // part b
   int m, n;
  
   printf("Enter m: ");
   scanf("%d", &m);
  
   printf("Enter n: ");
   scanf("%d", &n);
   if(m+n <= 0)
   {
       printf("Size should be more than
0.");
       return;
   }
   int *b = (int *)malloc(sizeof(int)*(m+n));
  
printf("\n--------------------------------------\n");
   // part c
   int x, y, z;
   printf("Enter x: ");
   scanf("%d", &x);
  
   printf("Enter y: ");
   scanf("%d", &y);
  
   printf("Enter z: ");
   scanf("%d", &z);
  
   if((x+y+z) <= 0)
   {
       printf("Size should be more than
0.");
       return;
   }
  
   int ***matrix, i, j;
  
   // this is how memory for 3D matrix is
allocated.
   matrix = (int ***)malloc(x * sizeof(int**));
  
   for(i = 0 ; i < x ; i++)
   {
       matrix[i] = (int **)malloc(y *
sizeof(int *));
       for(j = 0 ; j < y ; j++)
       {
           matrix[i][j] =
(int *)malloc(z * sizeof(int));
       }
   }
  
printf("\n--------------------------------------\n");
}