1// Use malloc to allocate memory
2ptr = (castType*) malloc(size);
3int *exampl = (int*) malloc(sizeof(int));
4// Use calloc to allocate and inizialize n contiguous blocks of memory
5ptr = (castType*) calloc(n, size);
6char *exampl = (char*) calloc(20, sizeof(char));
1#include <stdlib.h>
2
3void *malloc(size_t size);
4
5void exemple(void)
6{
7 char *string;
8
9 string = malloc(sizeof(char) * 5);
10 if (string == NULL)
11 return;
12 string[0] = 'H';
13 string[1] = 'e';
14 string[2] = 'y';
15 string[3] = '!';
16 string[4] = '\0';
17 printf("%s\n", string);
18 free(string);
19}
20
21/// output : "Hey!"
1
2// declare a pointer variable to point to allocated heap space
3int *p_array;
4double *d_array;
5
6// call malloc to allocate that appropriate number of bytes for the array
7
8p_array = (int *)malloc(sizeof(int)*50); // allocate 50 ints
9d_array = (int *)malloc(sizeof(double)*100); // allocate 100 doubles
10
11
12// use [] notation to access array buckets
13// (THIS IS THE PREFERED WAY TO DO IT)
14for(i=0; i < 50; i++) {
15 p_array[i] = 0;
16}
17
18// you can use pointer arithmetic (but in general don't)
19double *dptr = d_array; // the value of d_array is equivalent to &(d_array[0])
20for(i=0; i < 50; i++) {
21 *dptr = 0;
22 dptr++;
23}
24
1int *p = new int; // request memory
2*p = 5; // store value
3
4cout << *p << endl; // Output is 5
5
6delete p; // free up the memory
7
8cout << *p << endl; // Output is 0