c++ - 如何从方法返回未知大小的字节数组

标签 c++ arrays arduino

我有一个类可以解析一些传入的串行数据。解析后,方法应返回一个包含一些已解析数据的字节数组。传入数据的长度未知,因此我的返回数组将始终不同。

到目前为止,我的方法分配了一个比我需要返回的更大的数组,并用我的数据字节填充它,我保留了一个索引,以便我知道我在字节数组中放入了多少数据。我的问题是我不知道如何从实例方法返回它。

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
}

在其他语言上,这很容易做到,但我对 C++ 不是很精通,所以我完全被困住了。

谢谢!

最佳答案

您正在使用只有一点点 RAM 的微 Controller 。您需要仔细评估“未知长度”是否也意味着无限长度。你不能处理无限长度。可靠操作的最佳方法是使用最大大小的固定缓冲区设置。

此类操作的常见模式是将缓冲区传递给函数,然后返回已使用的内容。你的函数看起来很像许多 C 字符串函数:

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;
}

关于c++ - 如何从方法返回未知大小的字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646377/

相关文章:

c++ - 我可以重用我删除的变量或对象吗?

arrays - 如何将元素添加到 bash 数组?

c - 使用包含 float 数组的 OpenCL 将结构传递给 GPU

iOS 蓝牙键盘未注册 VoiceOver control+option/(CTRL+ALT) 键同时按下

c - 在arduino中通过串口读取整数

c++ - 成员(member)模板功能。为什么不编译?

c++ - 尾调用递归

arduino - 是否可以在 Arduino 中显示编译器警告?

c++ - 从闭源库中检索静态指针,不由公共(public)接口(interface)公开

javascript - 从数组 Ionic 2 Storage 中删除元素