Hey guys,
I'm going crazy for a week.
My project uses dynamic data, especially two-dimensional dynamic arrays I need.
The problem is that for a few elements works well, but sometimes when I try to add more items, it fails.
I cleaned up and simplified the code to be well understood.
I think the problem is "addSubItem", but I fail to see why.
Is it a bug? I'm a bug? XD
I'm using Arduino 0022 and MEGA2560
THX!! Greetings from Spain
struct typeSubItem {
int subitem;
};
struct typeItem {
int item;
typeSubItem** arraySubItem;
int arraySubItemSize;
};
typeItem** arrayItem = NULL;
int arrayItemSize = 0;
//=======================================================================
void addItem(int item) {
arrayItem = (typeItem**) realloc(arrayItem, (arrayItemSize + 1) * sizeof(typeItem*));
arrayItem[arrayItemSize] = (typeItem*) malloc(sizeof(typeItem));
arrayItem[arrayItemSize]->item = item;
arrayItem[arrayItemSize]->arraySubItem = NULL;
arrayItem[arrayItemSize]->arraySubItemSize = 0;
arrayItemSize++;
}
//=======================================================================
void addSubItem(int pos, int subitem) {
arrayItem[pos]->arraySubItem = (typeSubItem**) realloc(arrayItem[pos]->arraySubItem, (arrayItem[pos]->arraySubItemSize + 1) * sizeof(typeSubItem*));
arrayItem[pos]->arraySubItem[arrayItem[pos]->arraySubItemSize] = (typeSubItem*) malloc(sizeof(typeSubItem));
arrayItem[pos]->arraySubItem[arrayItem[pos]->arraySubItemSize]->subitem = subitem;
arrayItem[pos]->arraySubItemSize++;
}
//=======================================================================
void setup() {
int items = 10; // !!!!!!!!!! For (30, 10) it fails, for (10, 10) is OK
int subitems = 10;
Serial.begin(9600);
Serial.println("Processing...");
for (int i = 0; i < items; i++) {
Serial.println(i);
addItem(i);
delay(20);
for (int j = 0; j < subitems; j++) {
Serial.print("\t"); Serial.println(j);
addSubItem(i, j);
}
}
Serial.println("Done.");
}
//=======================================================================
void loop() {}