我有一个名为 datain 的 bitset<112>,它被填充在一个与主函数分开的函数中。我希望将 bitset 拆分为一个 14 字节的 uint8_t 数组,并将该数组返回给主函数。我写了一个 for 循环来做到这一点。我已经阅读了有关返回数组的指针的内容,这是我最好的机会。
uint8_t* getDataArray()
{
bitset<112> datain;
// code to populate datin here
i = 111;
uint8_t *byteArray = new uint8_t[14];
bitset<8> tempbitset;
for (int j = 0; j<14; j++)
{
for (int k = 7; k >= 0; k--)
{
tempbitset[k] = datain[i];
--i;
}
*byteArray[j] = tempbitset.to_ulong();
}
return byteArray;
}
int main()
{
uint8_t* datain = getDataArray();
}
但是这会导致编译错误
error: invalid type argument of unary '*' (have 'uint8_t {aka unsigned char}')|
在线
*byteArray[j] = tempbitset.to_ulong();
但是根据我对指针的理解,byteArray[j] 是数据的地址,而 *byteArray[j] 是数据,所以这应该可行吗???
谢谢。
编辑以消除我的编译器在我解决此错误后指出的另一个错误。
最佳答案
因为你有一个指针,所以你不需要在数组上取消引用和使用 operator[]
。指针指向数组中的第一个元素。如果你想要另一个元素,你可以只使用下标运算符,而不用担心取消引用。
只需这样做:
byteArray[j] = tempbitset.to_ulong(); //write to position j in the array.
关于c++ - 在 C++ 中从函数返回数组到 main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18380382/