I need to declare a double array (doubleArrayVariable[][]) which will be used in loop lots of times.
However I need to read a EEPROM value in setup() in order to define the array lenght.
The problem is that if I define it in setup(), then it won't be known in loop().
What could I do?
Declare it outside of both (global).
But I don't know the size until setup().
albuino:
But I don't know the size until setup().
Then declare a global pointer and use malloc() in setup. Post your code to get advice that isn't just stabbing in the dark.
#include <EEPROM.h>
byte variable[][];
setup() {
int size1 = EEPROM.read(0);
int size2 = EEPROM.read(1);
// Here I already know the sizes.
}
loop() {
// Handling variable.
}
byte **variable = NULL;
setup()
{
int size1 = EEPROM.read(0);
int size2 = EEPROM.read(1);
// Here I already know the sizes.
variable = (byte **)malloc(size1 * size2 * sizeof(byte);
}
void loop()
{
}
Very nice, I didn't know the malloc() funtion. The only doubt is that I am only used to managing double array by rows and columns. With this code how I know how many rows and columns there are?
byte **variable = NULL;
variable = (byte **)malloc(2 * 3 * sizeof(byte));versus
byte variable[2][3];
There is only one dimension, but you can fake rows and colums with soemthing like that:
#define setValue( row, col, value ) variable[ col + ( row * size2 ) ] = value
setValue( 1, 2, 10 )
//equivalent to
variable[1][2] = 10;
Ok it's crap..
Ok, actually the number of columns is always known. So it is only necessary reading a value from the EEPROM memory.
Why doesn't this code work?
byte *variable[2] = NULL;
setup()
{
int size = EEPROM.read(0);
variable = (byte[2] *)malloc(size * sizeof(byte[2]));
}
void loop()
{
}
because byte[2] * is no type.
guix:
There is only one dimension, but you can fake rows and colums with soemthing like that:#define setValue( row, col, value ) variable[ row + ( col * size2 ) ] = value
setValue( 1, 2, 10 )
//equivalent to
variable[1][2] = 10;
Ok it's crap..
Crap? Not at all. I really like it.
No, it really is crap without semicolons
I made a mistake in my code, it's more like this:
variable[ col + ( row * size2 ) ]
albuino:
Very nice, I didn't know the malloc() funtion. The only doubt is that I am only used to managing double array by rows and columns. With this code how I know how many rows and columns there are?
Does this help:
byte **variable = NULL;
int rows;
int cols;
void setup()
{
rows = EEPROM.read(0);
cols = EEPROM.read(1);
// Here I already know the sizes.
variable = (byte **)malloc(rows * cols * sizeof(byte));
}
void loop()
{
// "Handling variable" as you put it
for (int r=0; r<rows; r++)
for (int c=0; c<cols; c++) {
variable[r][c] = 17;
}
}