Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Language C++ (PLEASE ANSWER ALL PARTS) Write a program to dynamically allocate a

ID: 3774263 • Letter: L

Question

Language C++ (PLEASE ANSWER ALL PARTS)

Write a program to dynamically allocate a couple of arrays using malloc and calloc and see what they contain: Allocate an array of integers 5 elements long using calloc. Remember that calloc takes 2 parameters, the number of elements and the size (in bytes) for each element You may need to reinterpret_cast(calloc(...)) the call to calloc if your compiler doesn't like assigning the void * address returned by calloc to an int * pointer. Set the 3rd element of the array to 259. (That's 256 + 3...what is it in binary?) Print the contents of the array to verify that they have been initialized to zeros (except for the 3^rd element, which you just changed). Allocate an array of doubles 10 elements long using malloc. Be sure to allocate enough bytes! Remember that you tell malloc how many bytes you need, not how many elements. Set the 3rd element of the array to 259.0. Set the 4^th element of the array to 259.875. Print out the contents of the array, to see if they have been initialized or not (You may still get zeros...unused memory often contains zero's, but there's no guarantee with malloc) return the memory for both arrays to free-store using free(...) Name your program simple_malloc_calloc_free.cpp

Explanation / Answer

Array created with calloc will have elelements initialized with zero whereas array with malloc is not initialized with zero.

----------------------------------------------------------------------------------------------------------------------------------

#include<iostream>
using namespace std;

int main()
{
   //declare pointer variable which will point to memory location of array of 5 elements created by malloc

   double *array_malloc ;
   //declare pointer variable which will point to memory location of array of 5 elements created by calloc
   int *array_calloc;

   array_calloc =(int*) calloc(5,sizeof(int));
   //set 3rd element of array to 256
   array_calloc[3] = 256+3;

   //check if all the elements of the array initialized to zero except 3r element of array_calloc
   cout<<"Print array elements : ";
   for( int i = 0; i < 5 ; i ++ )
   {
       cout<<array_calloc[i]<<" ";
   }
   cout<<endl;
   //allocte array to hold 10 elements of double type using malloc
   array_malloc = (double*)malloc(10 * sizeof(double));
   array_malloc[3] = 259.0;
   array_malloc[4] = 259.875;
   //check if all the elements of the array initialized to zero except 3r element of array_calloc
   cout<<"Print array elements : ";
   for( int i = 0; i < 10 ; i ++ )
   {
       cout<<array_malloc[i]<<" ";
   }
   //free both pointers array_malloc, array_calloc
   free(array_malloc);
   free(array_calloc);
   cout<<"print "<<array_malloc[3]<<array_calloc[3]<<endl;

}