Using C Programing Write Code Snippet Using Malloc Allocate Array 10 Integers Must Declare Q37132710

Using C Programing

Write a code snippet using malloc() to allocate an array of 10integers. You must declare all variables and arrays correctly.


Solution


#include <stdio.h>
#include <stdlib.h>
int main()
{
int *a = NULL, n = 10, i = 0;

a = (int *)malloc(n * sizeof(int));

//Check memory validity
if(a == NULL)
{
return 1;
}

//copy i to each block of 1D Array and print the copieed data
for (i =0 ; i < 10 ; i++)
{
a[i] = i;
printf(“a[%d] = %dn”, i,a[i]);
}

free(a); // free allocated memory

return 0;
}

Output :

a[0] = 0 a[1] = 1 a[2] 2 а[3] 3 a[4] = 4 ia [5] = 5 a[6] 6 a[7] =1 a[8] = 8 а[9] 9

a[0]

OR
OR

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.