0

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.

  • @jsotola I know. I was tired when I posted this question, so excuse my typo – prehfeldt Jul 24 '18 at 8:12
5

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.