2

Been in C#-land for a while and I can't work out how to do this in C++ (in an Arduino sketch)

I would like to call a function from a library that returns a list of bytes of unknown length. Sort of like this:

byte devices[] = MyLib::EnumerateDevices();

And in the library:

byte[] MyLib::EnumerateDevices()
{       
   int count = 0;       

   //some code that modifies count

   static byte *temp = new byte[count];  // Assume count is 2 here

   temp[0] = 42;
   temp[1] = 44;       

   return temp;
}

Obviously I have all me pointers and derefs either missing or in the wrong place...

Help?

Dave

2
  • You'll need some way to pass the length of the array as well, unless you can deduce the length just from the byte sequence? Commented Jul 24, 2013 at 14:37
  • The arduino uses AVR libc which does not support new and delete: nongnu.org/avr-libc/user-manual/FAQ.html#faq_cplusplus Commented Jul 24, 2013 at 16:08

2 Answers 2

7

This is what vectors are for:

std::vector<int> func()
{
    std::vector<int> r;
    r.push_back(42);
    r.push_back(1337);
    return r;
}

Vectors have a size() member function which returns exactly what you want.

If you want a pointer out of the vector, then write

const int *p = &vec[0];

(obviously, substitute int with whatever type you specialized the vector with.)

Sign up to request clarification or add additional context in comments.

5 Comments

These days, you could shorten that to return {42, 1337};, if you like brevity.
@MikeSeymour well, yes. My go was only to show that "here you do stuff with the vector and then return it" :)
std::vector (and the rest of the STL) is not available on arduino.
@Craig Then you need to pass a size_t argument by reference.
Sorry, a bit pissed. The question specified variable-length arrays in C++, NOT vectors! (Feel free to delete this comment now...)
2

You can't return an array in C or C++. You can return a pointer, but in this case, you would also need to return the size. Use std::vector<int> instead, much easier.

1 Comment

You can return an array, either as a struct/class member or a std::array<>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.