0

I have a class that parses some incoming serial data. After the parsing a method should return a byte array with some of the parsed data. The incoming data is of unknown length so my return array will always be different.

So far my method allocates an array bigger than what I need to return and fills it up with my data bytes and I keep an index so that I know how much data I put in the byte array. My problem is that I don't know how to return this from an instance method.

void HEXParser::getParsedData()
{
    byte data[HEX_PARSER_MAX_DATA_SIZE];
    int dataIndex = 0;

    // fetch data, do stuff
    // etc, etc...

    data[dataIndex] = incomingByte;
    _dataIndex++;

    // At the very end of the method I know that all the bytes I need to return
    // are stored in data, and the data size is dataIndex - 1
}

On other languages this is trivial to do but I'm not very proficient in C++ and I'm completely stuck.

Thanks!

3
  • 3
    Use std::vector. Commented Jul 15, 2013 at 3:37
  • data should be dynamically allocated if you wants to return it Commented Jul 15, 2013 at 3:37
  • 1
    ahhhhh, not on a microcontroller. Stay off the heap. Commented Jul 15, 2013 at 3:40

1 Answer 1

2

You are working on a microcontroller with just a little bit of RAM. You need to carefully evaluate if "unknown length" also implies unbounded length. You cannot deal with unbounded length. Your best approach for reliable operation is to use fixed buffers setup for the maximum size.

A common pattern for this type of action is to pass the buffer to the function, and return what has been used. Your function would then look much like many of the C character string functions:

const size_t HEX_PARSER_MAX_DATA_SIZE = 20;
byte data[HEX_PARSER_MAX_DATA_SIZE];

n = oHexP.getParsedData(data, HEX_PARSER_MAX_DATA_SIZE);

int HEXParser::getParsedData(byte* data, size_t sizeData)
{
  int dataIndex = 0;

  // fetch data, do stuff
  // etc, etc...

  data[dataIndex] = incomingByte;
  dataIndex++;
  if (dataIndex >= sizeData) {
     // stop
  }

  // At the very end of the method I know that all the bytes I need to return
  // are stored in data, and the data size is dataIndex - 1

  return dataIndex;
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1: letting the caller handle allocation is very appreciated in APIs used by perf-conscious code.

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.