简体   繁体   English

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

[英]returning array from function to main in c++

I have a bitset<112> called datain which is populated in a function seperate to the main one. 我有一个叫做datain的bitset <112>,它填充在与主函数分开的函数中。 I wish to split the bitset into an array of 14 bytes of uint8_t and return this array to the main function. 我希望将位集分成uint8_t的14个字节的数组,并将该数组返回给main函数。 I have written a for loop to do this. 我已经写了一个for循环来做到这一点。 I have read about pointers to return an array and this is my best shot. 我已经阅读了有关返回数组的指针的信息,这是我的最佳镜头。

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

However this gives a compile error 但是这会产生编译错误

error: invalid type argument of unary '*' (have 'uint8_t {aka unsigned char}')|

On the line 在线上

*byteArray[j] = tempbitset.to_ulong();

But from what I understand about pointers, byteArray[j] is the address for the data, and *byteArray[j] is the data so this should work??? 但是从我对指针的了解来看,byteArray [j]是数据的地址,而* byteArray [j]是数据,因此应该可以使用???

thanks. 谢谢。

edited to take out another error my compiler pointed out once I had solved this error. 一旦解决了这个错误,我的编译器便指出编辑出另一个错误。

Because you have a pointer, you don't need to dereference and use operator[] on the array. 因为有指针,所以不需要取消引用并在数组上使用operator[] The pointer points to the first element in the array. 指针指向数组中的第一个元素。 If you want another element, you can just use the subscript operator, without worrying about dereference. 如果需要其他元素,则可以使用下标运算符,而不必担心取消引用。

Just do this: 只要这样做:

byteArray[j] = tempbitset.to_ulong(); //write to position j in the array.  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM