i want to create a somewhat complex structure of classes in an arduino. The short story is: a Device has Presets, and each Preset has a Patterns. For that i created the following structure (i am only posting the important stuff, if something is missing let me know):
INO file
#include "LedDevice.h"
LedDevice device;
void setup() {
device = LedDevice(10, 10, 10);
}
void loop() {
Serial.println(F("Ticking"));
device.Tick();
delay(500);
}
LedDevice
#if !defined(_LEDDEVICE_H)
#define _LEDDEVICE_H
#include "Preset.h"
#include<Arduino.h>
class LedDevice {
public:
Preset* Presets[];
LedDevice(){}
LedDevice(int numPixels, int numPresets, int numPatterns)
{
*Presets = (Preset*)malloc(sizeof(Preset) * numPresets);
for (int p = 0; p < numPresets; p++)
{
Presets[p] = new Preset("test", numPixels, numPatterns);
}
}
void Tick()
{
Serial.print(F("Preset ")); Serial.println(Presets[0]->Name);
Presets[0]->Tick();
}
};
#endif //_LEDDEVICE_H
Preset
#if !defined(_PRESET_H)
#define _PRESET_H
#include "Pattern.h"
class Preset {
public:
char *Name;
int NumPatterns;
Pattern* Patterns[];
Preset(char* name, int numPixels, int numPatterns) : NumPatterns(numPatterns)
{
Name = (char *)malloc(strlen(name) + 1);
strcpy(Name, name);
*Patterns = (Pattern*)malloc(sizeof(Pattern) * NumPatterns);
for (int p = 0; p < NumPatterns; p++)
{
Patterns[p] = new Pattern(numPixels);
}
}
void Tick()
{
for (int p = 0; p < NumPatterns; p++)
{
Patterns[p]->Tick();
}
}
};
#endif
Pattern
#if !defined(_PATTERN_H)
#define _PATTERN_H
class Pattern {
public:
Pattern(int numPixels){}
void Tick(){}
};
#endif
The code compiles but when i run the full version (this is a simplified version of the code) i get some strange behavior, so i would like to know if i am doing the initialization of the Presets and Patterns correctly.
Also when i try to print the Preset name in the LedDevice Tick function i get strange characters, so either i am not initializing the string correctly or the pointers to the Presets are wrong.
Can you tell if anything is not being done correctly in the constructors?
new
does is: allocate memory for an object and construct the object. Doesn't*Presets = (Preset*)malloc(sizeof(Preset) * NumPresets);
allocate memory for an array ofPreset
s andfor ... Presets[p] = new Preset(...)
allocate the same amount again? (This would be a problem, not the problem.) – James Waldby - jwpat7 Feb 23 '17 at 17:59