c++ - 在 C++ 中从函数返回数组到 main

标签 c++ arrays pointers

我有一个名为 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/

相关文章:

c++ - C++ 函数定义中的 "Type&"与 "Type*"

c++ - 在 NSData 中存储 C++ 结构/对象

c++ - 找不到标识符 : __mul128

c++ - 半边双胞胎

php - 如何在同一个 feed 中输出多个数组

C:结构是作为指针实现的吗?

c++ - 调用运算符参数评估顺序

ruby - Ruby 数组与哈希测试中的堆栈级别太深

c - 拆分文件中的字符串并将值保存在数组中会打印错误的输出

c - 全局指针值丢失。 2个文件