Dynamic memory allocation
We learned earlier that the amount of memory usable by statically allocated arrays, like that:
Let us learn to dynamically allocate them, so the only limit is the amount of free memory the computer has.
Before continuing, we have to learn to manually convert between variable types. When the conversion is done automatically, we say it is 'implicit':
int var = 6; long var2 = var; // Automatic conversion 'int' -> 'long'.
We can manually (explicitly) convert a variable, like that:
long var2 = (long)var; // Explicit conversion.
The operator sizeof
The operator sizeof returns the size, in bytes, of a type.
Here we print the size of the type 'int':
It can also be used to retrieve the size, in bytes, of a statically allocated array:
int array; printf("%d == %d * %d.\n", sizeof(array), 20, sizeof(int));
Pointer of type void
A pointer of type void, like such:
Points to a variable of unknown type.
Here we define an array of bytes (Remember, the type 'char' always weights 1 byte), of the size of the type 'int':
We make the 'void' pointer point to the beginning of the array:
ptr = bytes;
By explicitly casting the 'void' pointer to a pointer of type 'int', we can use the array as if it was a variable of type 'int':
int *intPtr = (int*)ptr; *intPtr = 60;
To avoid creating an other pointer, we can also write:
*((int*)ptr) = 60;
Above, we cast the pointer to a pointer of type 'int'. Then we access the 'variable' that it points to and we assign the value 60 to the array of bytes that is interpreted as a variable of type 'int'.
Dynamically allocating memory
The function 'malloc' returns a pointer of type 'void', pointing to a dynamically allocated byte array of the size of the number it received in argument.
The function 'malloc' is declared in the header file <stdlib.h>:
Here we allocate 50 bytes:
Here we allocate enough bytes for 10 variables of type 'float' and we cast the returned pointer to a pointer of type 'float':
float *floatArray = (float*) malloc(10 * sizeof(float));
We access the first element of the array:
floatArray = 67;
And the last one:
floatArray = 15;
Using the function 'realloc', we can change the size of an array allocated with malloc:
// Allocates 4 'int'. int *intArray = (int*) malloc(4 * sizeof(int)); // Changes the size to 8 'int'. intArray = (int*) realloc(intArray, 8 * sizeof(int));
Unlike statically allocated memory, dynamically allocated memory must be manually freed. When we are done using memory allocated with 'malloc', we must free it using the function 'free':