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]
OR
OR