Write a program to ask the user to enter the total number of float data. Then use the calloc() and malloc() functions to allocate two memory blocks with the same size specified by the number, and print out the initial values of the two mem- ory blocks.
My solution is:
float *p_1,*p_2;
int i,num_of_floats=0;
printf("the total number of float numbers: ");
scanf("%d",&num_of_floats);
if((p_1=calloc(num_of_floats,sizeof(float)))==NULL||(p_2=malloc(num_of_floats*sizeof(float)))==NULL){
printf("error at alllocating!!\n");
exit(1);
}
else{
for(i=0; i<num_of_floats ;i++){
printf("%f",*(p_1+i));
}
printf("\n");
for(i=0; i<num_of_floats ;i++){
printf("%f",*(p_2+i));
}
}
free(p_1);
free(p_2);
return 0;
output:
the total number of float numbers: 5
0.0000000.0000000.0000000.0000000.000000
0.0000000.0000000.0000000.0000000.000000
The malloc function doesn't Initialize the values to zero, and still i get zeros.