如何在C ++中返回字符数组?数组长度由函数本身确定

how to return char array in c++? array length is determined in the function itself

本文关键字:数组 函数 返回 字符      更新时间:2023-10-16
char *readByteArray() {
    unsigned char l = readByte (); // reads one byte from the stream
    char ret[l + 1]; // this should not be done
    ret[0] = l; // or could also define a struct for this like {int length, char *data}
    readBytes((char *)&ret + 1, l);
    return (char *)&ret;
}

所以问题是,我想返回一个数组,数组的长度由函数决定。

一个更好的例子是我用于读取字符串的函数:

char *readString () {
    unsigned char l = readByte (); // reads one byte from the stream
    char ret[l + 1]; // +1 for null byte
    readBytes((char *)&ret, l); // reads l bytes from the stream
    ret[l] = ''; // null byte
    return (char *)&ret; // problem
}

如果数组的长度是在函数之前确定的,我可以在函数外部分配数组并将其作为参数传递,但调用这个:

unsigned char l = readByte ();
char ret[l + 1];
readString (&ret, l);

每次我想读取字符串时都会破坏函数的目的。

在Windows和ATmega328上是否有优雅的解决方案(STL不可用(?

以下选项之一应该有效:

  1. 返回指向从堆分配的char数组的指针。确保删除调用函数中的返回值。

    char* readByteArray()
    {
       unsigned char l = readByte();
       char *ret = new char[l + 1];
       ret[0] = l;
       readBytes(ret + 1, l);
       return ret;
    }
    
  2. 返回std::vector<char> .

    std::vector<char> readByteArray()
    {
       unsigned char l = readByte();
       std::vector<char> ret(l);
       readBytes(ret.data(), l);
       return ret;
    }