Post the code in code tags so the forum doesn't mess up the array indexes.
Read the forum guidelines to see how to properly post code. Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.
char myarray[] = "abcdef";
int len = sizeof(myarray);
char temp[] = "0 ";
void setup()
{
Serial.begin(115200);
for (int i = 0; i < len - 1 ; i++)
{
temp[0] = myarray[i];
Serial.println(myarray[i]);
showOledMsg(8, 3, temp);
delay(500);
}
Serial.println("_____________________");
}
void loop() {}
I don't have your OLED display and you didn't how how it was initialized but when I comment out the one OLED line, the rest of the sketch compiles without error or warning and produces the expected output on Serial:
Yes. For strings it should be < len - 1 when sizeof() is used (or strlen and < len) but for any other data representation in char form (for example binary data like audio samples) it should strictly be sizeof() and reading till < len. Using strlen() in this case will fail since binary data streams can contain the null terminating character mid-stream as well.
Typically native or OS APIs (in Windows, atleast) never return char buffers (not strings) just as an array and expect the calling code to infer its length. It is something like this:
// Function that returns a char buffer
void get_buffer(char** buf, int& szLen)
// OR
//void get_buffer(char** buf, size_t& szLen)
{
(*buf) = new char[10]; // allocate 10 bytes for example
//Fill data in the buffer
szLen = 10;
}
// Usage
char* myBuf = ""; //Initialisation may or may not be done.
int bufLen;
/// Call get_buffer()
get_buffer(&myBuf, &bufLen);
for(int i = 0; i < bufLen; i++)
{
// Use the buffer data
char elem = myBuf[i];
Serial.write(elem); // Just an example
}
delete[] myBuf; // Clean up
I have never seen the Windows API behave like that. Normally you would pass a null-buffer to a function to get the required buffer size and use "new" or "malloc" to reserve that buffer before recalling the function with a valid buffer. Your example is also leaking memory, btw.
Have a look at the DirectSound8 or WaveIn/WaveOut or the setUpDiXXX (these relate to HID) APIs. They return an interface by expecting the address of a pointer.
I may have mixed it up with this, but the method I outlined is when the called function allocates memory versus the caller allocating it.
As for the memory leak, that is something from memory and may not be perfect - the caller has to clean up - updated the code for this. Basically I had to do it this way to send audio data (char*) via platform-invoke to .NET code.
Yes the way you suggested is also done -call it twice, once for the expected size, then allocate memory and then call with the actual buffer and sz parameter as zero.