dynamically allocate size of array in loop?

Hi,

I statically declare an array as 100 bytes. Then I open a file and read out 100 bytes, do something and then get the next 100 and do something etc.

But when I get to the end of the file there is not exactly 100 bytes as the file sizes are uneven.

I base64 encode the arrays. When I encode the last array I end up with extra characters due to the empty elements in the array.

How can I dynamically allocate only the size that I need for the last array? Or is there another solution?

Thanks

#include <SD.h>

File myFile;
uint8_t myBytes[100];
int i;


void setup()
{

//open the file for reading:
  myFile = SD.open("pic.jpg");
  int sizefile = myFile.size();
  Serial.println(sizefile);
  
  if (myFile)
  {
    for(int s = 0; s < myFile.size(); s+=100){
      Serial.println(s);
      delay(2000);
      myFile.seek(s);
    
      for (int aByte = 0; aByte < 100; aByte++){
        myBytes[aByte] = myFile.read();  //put the byte read from the file into the array
        }
        //encode the array
        }
  }
}

void loop()
{
}

But when I get to the end of the file there is not exactly 100 bytes as the file sizes are uneven.

But, you know how many you read (or you should, since the function told you (or tried to)).

I base64 encode the arrays. When I encode the last array I end up with extra characters due to the empty elements in the array.

You need to pad the array with NULLs, then.

How can I dynamically allocate only the size that I need for the last array?

The function you are using to encode the array expects arrays of a certain size. If you pass it a smaller array, it will still read beyond the end, producing garbage. So, while malloc() or new could be used to allocate a smaller array, it will not solve your problem.

Base64 encoding usually works 16 bytes at a time, so an array of 100 is a strange size, anyway. Powers of 2 make far better choices than powers of 10 (1, 2, 4, 8, 16, 32, 62, 128, etc., not 10, 100, 1000).