#include <stdio.h>
#include <stdlib.h>
void main()
{
double *ary; //will be your dynamic 1d array
int num; //your array element
//input your number of array element
printf("num: ");
scanf("%d", &num);
//syntax: number of block address times byte needed (sizeof) for double variable
ary = malloc(num * sizeof(double));
//fill the array (can be changed to any number) and display them
for(int i=0; i<num; i++)
{
ary[i] = i * i * 2.8;
printf("%.2f\n", ary[i]);
}
//must free the memory allocation to not make memory leak
if(ary) free(ary);
}
dynimcally allocated array 2
Tuesday, May 30, 2017
dynamically allocated 2d array using an array of pointers
Thursday, May 18, 2017
#include <stdio.h>
#include <stdlib.h>
void main()
{
int row = 5, col = 3;
int i, j;
double *ar[row]; //will be your 2d array
for(i=0; i<row; i++) //make it into 2d array
ar[i] = malloc(sizeof(int)*col); //get the column number of array
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
ar[i][j] = (i + j) * 1.0; //filling the array element
}
}
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
printf("[%d][%d]=%.2f ", i, j, ar[i][j]); //print the array after filling it
}
printf("\n");
}
//must free the memorry allocation after using it
for(i=0; i<row; i++)
free(ar[i]);
}
result:
[0][0]=0.00 [0][1]=1.00 [0][2]=2.00
[1][0]=1.00 [1][1]=2.00 [1][2]=3.00
[2][0]=2.00 [2][1]=3.00 [2][2]=4.00
[3][0]=3.00 [3][1]=4.00 [3][2]=5.00
[4][0]=4.00 [4][1]=5.00 [4][2]=6.00
dynamically allocated array
Friday, May 12, 2017
#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
Subscribe to:
Posts (Atom)