dynamic memory allocation in c programming examples
Example 1: 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 2: c malloc array
#define ARR_LENGTH 2097152
int *arr = malloc (ARR_LENGTH * sizeof *arr);
Example 3: c++ program to input and print text using Dynamic Memory Allocation.loop
program to input and print text using Dynamic Memory Allocation.