如何在C ++中返回字符数组?数组长度由函数本身确定
how to return char array in c++? array length is determined in the function itself
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不可用(?
以下选项之一应该有效:
-
返回指向从堆分配的
char
数组的指针。确保删除调用函数中的返回值。char* readByteArray() { unsigned char l = readByte(); char *ret = new char[l + 1]; ret[0] = l; readBytes(ret + 1, l); return ret; }
-
返回
std::vector<char>
.std::vector<char> readByteArray() { unsigned char l = readByte(); std::vector<char> ret(l); readBytes(ret.data(), l); return ret; }
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 打印 2D 动态数组 c++ 函数
- C++数组函数
- 在数组函数指针中调用void
- 数组函数似乎没有找到最大值
- 使用数组函数和循环求解伪元编码|C
- 在头文件中的函数原型中获取指针数组:函数声明为 void
- 数组函数错误输出
- 读取文件,然后创建数组函数C++
- 指针数组函数参数-奇怪的行为
- 二维数组 - 函数
- "return"没有从数组函数返回正确的值
- 数组函数问题
- 数组函数的大小返回 int 的大小而不是数组
- 从数组函数中删除元素
- 如何从C++中最好地调用具有C99风格数组函数签名的函数
- 追加/打印/插入数组c++函数问题
- 如何将数组函数转换为指针函数
- 多维数组函数输出垃圾
- C++:数组函数的递归最大值