calloc and malloc code example
Example 1: allocate memory c
ptr = (castType*) malloc(size);
int *exampl = (int*) malloc(sizeof(int));
ptr = (castType*) calloc(n, size);
char *exampl = (char*) calloc(20, sizeof(char));
Example 2: malloc in c
#include <stdlib.h>
void *malloc(size_t size);
void exemple(void)
{
char *string;
string = malloc(sizeof(char) * 5);
if (string == NULL)
return;
string[0] = 'H';
string[1] = 'e';
string[2] = 'y';
string[3] = '!';
string[4] = '\0';
printf("%s\n", string);
free(string);
}
Example 3: 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 4: how to use malloc in c
int* a =(int*)malloc(sizeof(int))
Example 5: Malloc
ptr = malloc(size);
Example 6: how to use malloc in c
ptr = (cast-type*) malloc(byte-size)