allocate array with 0 using malloc code example
Example 1: how to dynamically allocate array size in c
int *p_array;
double *d_array;
p_array = (int *)malloc(sizeof(int)*50);
d_array = (int *)malloc(sizeof(double)*100);
for(i=0; i < 50; i++) {
p_array[i] = 0;
}
double *dptr = d_array;
for(i=0; i < 50; i++) {
*dptr = 0;
dptr++;
}
Example 2: n no of array in c using malloc
#include <stdio.h>
int main()
{
printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
int n, i, *ptr, sum = 0;
printf("\n\nEnter number of elements: ");
scanf("%d", &n);
ptr = (int *) malloc(n*sizeof(int));
if(ptr == NULL)
{
printf("\n\nError! Memory not allocated\n");
return 0;
}
printf("\n\nEnter elements of array: \n\n");
for(i = 0; i < n; i++)
{
scanf("%d", ptr+i);
sum = sum + *(ptr + i);
}
printf("\n\nThe elements of the array are: ");
for(i = 0; i < n; i++)
{
printf("%d ",ptr[i]);
}
free(ptr);
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
}