An example of how to allocate and deallocate memory for 2-D arrays. But: See Footnote.
void setup()
{
Serial.begin(9600);
}
int counter = 0;
void loop()
{
// Pointer to pointer will be used to implement 2-D dynamically allocated array
int **iarray;
int nrows = 2;
int ncols = 3;
// Allocate an "array" of pointers for the rows
iarray = (int**)malloc(nrows*sizeof(iarray[0]));
if (!iarray) {
Serial.print("Couldn't allocate memory for rows.");
return;
}
// For each row, allocate an "array" of ints.
for (int i = 0; i < nrows; i++) {
iarray[i] = (int *)malloc(ncols*sizeof(iarray[0][0]));
if (!iarray[i]) {
Serial.print("Couldn't allocate memory for row ");
Serial.println(i);
return; // Actually you should de-allocate memory for all
// of the rows that did get allocated and then
// de-allocate memory for iarray.
}
for (int j = 0; j < ncols; j++) {
iarray[i][j] = counter + j + ncols*i; // Put something different in each one
}
}
for (int i = 0; i < nrows; i++) {
Serial.print("Row ");Serial.print(i);Serial.print(": ");
for (int j = 0; j < ncols; j++) {
Serial.print(" ");Serial.print(iarray[i][j]);
}
Serial.println();
}
Serial.println();
// De-allocate storage for each of the rows
for (int i = 0; i < nrows; i++) {
free(iarray[i]);
}
// Deallocate storage for the array of row pointers
free(iarray);
// After previous memory has been cleared, you can reallocate with
// whatever values of nrows and ncols you want (subject to "heap"
// size limits).
++counter;
delay(1000);
}
Output:
Row 0: 0 1 2
Row 1: 3 4 5
Row 0: 1 2 3
Row 1: 4 5 6
Row 0: 2 3 4
Row 1: 5 6 7
Row 0: 3 4 5
Row 1: 6 7 8
Row 0: 4 5 6
Row 1: 7 8 9
.
.
.
This is just an illustration of how to do it. In your loop() you would deallocate the storage then assign new values to nrows and ncols and go through the allocation steps again. I might even write a function to allocate storage for nrows and ncols and another function to deallocate them. I'll leave that up to you.
Regards,
Dave
Footnote:This example is (I believe) perfectly valid C and C++ code.
However...
I am very reluctant to use dynamic memory allocation in any embedded system that I expect to run forever. Why do I have misgivings? Lack of garbage collection in the standard library function malloc(). That's why.
It is possible to allocate and deallocate memory (repeatedly) in such a way that there is enough memory in the heap to do the job but it is fragmented so that that not enough
contiguous memory is available to finish it.
I mean, if the application is supposed to do something and quit, that's one thing, but if it is supposed to run forever and you don't know ahead of time how much memory you actually need, then, you are really, really (
really) asking for trouble. For simple cases, you might convince yourself that such fragmentation will not occur, but...
That's just an opinion (my opinion), and it's worth exactly what you want it to be worth.