new/delete
Operaror new allocates memory in heap for variables, objects, structures, arrays. This is an analogue of the malloc () function in C++. Operator delete releases memory area, that was allocated by means of new operator. Allocation of memory for a single variable/object: ptrArray = new typedelete ptrArray
ptrArray: name of pointer. type: Variable type. This could be a base type like int, float, char, double or name of class, typedef and etc.
#define MY_SERIAL Serial
void setup() {
int *ptrI;// pointer to store address of allocated data
MY_SERIAL.begin(115200);
ptrI = new int; // Allocate one int variable in the "heap"
*ptrI = rand(); // Fill it with random value
MY_SERIAL.print("raw data:");
MY_SERIAL.dumpPrint(ptrI, sizeof(int)); // Print raw data
MY_SERIAL.print("\nInteger value:");
MY_SERIAL.print(*ptrI); // Print integer value
delete ptrI; // free "heap" memory
}
void loop() {
}
Allocation memory for an array:
ptrArray = new type[size]delete[] ptrArray
ptrArray: pointer to memory area which holds the array. type: Array element's type. This could be a base type like int, float, char, double or name of class, typedef and etc. size: Required size of array.
#define MY_SERIAL Serial
void setup() {
int *ptrArray; // Pointer to array
MY_SERIAL.begin(115200);
ptrArray = new int[10]; // allocate 10 elements
for (int i = 0; i <5; i++)
ptrArray[i] = rand();// Fill element with random data
// print array to serial
MY_SERIAL.print("Array: ");
for (int i = 0; i <5; i++){
MY_SERIAL.print(" ");
MY_SERIAL.print(ptrArray[i]);
}
MY_SERIAL.println();
delete[] ptrArray; // Free allocated memory
}
void loop() {
}
Allocate memory for object
#include "Arduino.h"
#include "ZUNO_DHT.h"
#define MY_SERIAL Serial
DHT *dht22_sensor;
/* the setup function runs once, when you press reset or power the board */
void setup() {
dht22_sensor = new DHT(9, DHT22); // allocates memory region and then calls constructor of class for this region
MY_SERIAL.begin(115200);
dht22_sensor->begin();
MY_SERIAL.println("\n **** Sketch is starting... ****\n");
}
/* the loop function runs over and over again forever */
void loop() {
byte result;
byte i;
byte raw_data[5];
MY_SERIAL.print("Millis:");
MY_SERIAL.println(millis());
result = dht22_sensor->read(true); // We use -> instead of . to access methods of object located by dht22_sensor pointer
MY_SERIAL.print("DHT read result:");
MY_SERIAL.println(result);
MY_SERIAL.print("Raw data: { ");
dht22_sensor->getRawData(raw_data);
for(i=0;i<5;i++) {
MY_SERIAL.print(raw_data[i], HEX);
MY_SERIAL.print(" ");
}
MY_SERIAL.println("} ");
MY_SERIAL.print("Temperature:");
MY_SERIAL.println(dht22_sensor->readTemperature());
MY_SERIAL.print("Humidity:");
MY_SERIAL.println(dht22_sensor->readHumidity());
delay(3000);
}
Please note that you need required memory area to use dynamic memory operations. See malloc() description for details.