I'm trying to return a File* from a method like the one mocked below. How can I do this?
#include <SD.h>
#include <SPI.h>
File* createNewFile(char* filename)
{
SD.remove(filename);
File newFile = SD.open(filename, FILE_WRITE));
if(!newFile)
{
Serial.println("ER-FILE-02");
}
return &(newFile); // returns a File* that points to a valid File obj. Only problem is the obj
// is undefined after the very next line
}
Do I malloc sizeof(file) then memcpy() the bytes from newFile to mallocedFilePtr?
Since its stack, I thought that when the method ends the object becomes undefined. For instance:
int* getBadPointer()
{
int x = 10;
return &x;
}
Using an address of a local variable that goes out of scope is undefined behavior from the time it goes out of scope forward (as far as I remember at least, although I could def be wrong).
The way I understand it, if I make "static File f;" it sets aside enough memory for a File object and "f" is how I get to the start of that memory. If I do "f = newFile" it copies newFile to the "f" location, so that when the function ends and newFile goes out of scope (and is now unsafe / undefined), it doesn't matter because I coppied it over to my safe memory.
'static File newFile;' creates an object of the File class. Because it's static, the object remains valid even after the function exits -- and even after 'newFile' goes out of scope.
The 'SD.open()' method returns an object of the File class. 'newFile = SD.open' calls the (possibly default) 'operator=' method of the File class on newFile setting it equal to the object returned by 'SD.open()'.
Finally 'return &newFile;' returns a pointer to the File object as you wanted. Because the object is static, it (and the pointer to it) remain valid even after the function returns and newFile goes out of scope.
'static File newFile;' creates an object of the File class. Because it's static, the object remains valid even after the function exits -- and even after 'newFile' goes out of scope.
The 'SD.open()' method returns an object of the File class. 'newFile = SD.open' calls the (possibly default) 'operator=' method of the File class on newFile setting it equal to the object returned by 'SD.open()'.
Finally 'return &newFile;' returns a pointer to the File object as you wanted. Because the object is static, it (and the pointer to it) remain valid even after the function returns and newFile goes out of scope.
ohhh, I misunderstood you. okay great thanks a lot!