Friday, May 12, 2017

dynamically allocated array

 #include <stdio.h>  
 #include <stdlib.h>  
   
 void main()  
 {  
     double *ar; //will be your array  
     double elem[] = {0.1, 0.2 ,0.3 ,0.4 ,0.5};   
     int num = 5, i;  
   
     printf("array number: %d\n", num);  
     for(i=0; i<num; i++)  
         printf("[%d]:%.2f\n", i, elem[i]);  
   
     printf("lets double it and put in your new array using malloc\n");  
     printf("--\n");  
   
     ar = malloc(sizeof(double)*num); //allocate the memory for your array  
   
     for(i=0; i<num; i++){  
       *(ar+i) = elem[i] * 2;  
     }  
   
     for(i=0; i<num; i++)   
         printf("array[%d]=%.2f\n", i, ar[i]);  
   
 free(ar); //must free the memorry allocation after using it  
 } 
 
result:
-------------- 
 array number: 5
[0]:0.10
[1]:0.20
[2]:0.30
[3]:0.40
[4]:0.50
lets double it and put in your new array using malloc
--
array[0]=0.20
array[1]=0.40
array[2]=0.60
array[3]=0.80
array[4]=1.00 

No comments:

Post a Comment