I have the following piece of code which opens a Bitmap from the SD card and outputs the width to the serial monitor.
#include <SPI.h>
#include <SD.h>
File bitmap;
void setup() {
Serial.begin(9600);
Serial.println("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
bitmap = SD.open("/TEST2.BMP");
int width[0]; // why can't I just write "int width;"
bitmap.seek(18);
bitmap.read(width, 4);
Serial.println(width[0]); // and "Serial.println(width);"
}
void loop() {
}
It works perfectly fine but I don't understand why I have to declare the buffer for the width as int width[0];
. I tried int width;
but then the output is just 0.
2 Answers 2
You don't have to, it's just one way of doing it.
Basically the read
function needs a pointer to a buffer to store the data in. By using an array with one entry you get a pointer to a buffer that is big enough for one (32-bit) integer. And you then get an "easy" way of accessing that one integer within that buffer.
Another way would be to just use a simple integer and pass a pointer to that integer to read
:
uint32_t width; // Use a fixed size integer for portability
bitmap.seek(18);
bitmap.read(&width, sizeof(width)); // Use sizeof for portability
Serial.println(width);
I think I have a bit of insight:
An array is a pointer. Thus,
int arr[0];
is equivalent of
int * simple;
So. read(arr... or read(&simple...