dynamic memory allocation c code example
Example 1: c allocate array
int *array = malloc(10 * sizeof(int));
Example 2: allocate memory c
// Use malloc to allocate memory
ptr = (castType*) malloc(size);
int *exampl = (int*) malloc(sizeof(int));
// Use calloc to allocate and inizialize n contiguous blocks of memory
ptr = (castType*) calloc(n, size);
char *exampl = (char*) calloc(20, sizeof(char));
Example 3: 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);
}
/// output : "Hey!"
Example 4: how to use malloc in c
ptr = (cast-type*) malloc(byte-size)
Example 5: dynamic memory allocation in c++
char* pvalue = NULL; // Pointer initialized with null
pvalue = new char[20]; // Request memory for the variable
Example 6: dynamic memory allocation in c++
#include <iostream>
using namespace std;
int main () {
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
*pvalue = 29494.99; // Store value at allocated address
cout << "Value of pvalue : " << *pvalue << endl;
delete pvalue; // free up the memory.
return 0;
}