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

时间:2013-08-22 12:26:14

标签: c++ arrays pointers

我有一个位置< 112>称为datain,它填充在一个与主要函数分开的函数中。我希望将bitset拆分为一个14字节的uint8_t数组,并将该数组返回给main函数。我写了一个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]是数据,所以这应该工作???

感谢。

编辑以解决我的编译器在解决此错误后指出的另一个错误。

1 个答案:

答案 0 :(得分:1)

因为你有一个指针,所以你不需要取消引用并在数组上使用operator[]。指针指向数组中的第一个元素。如果你想要另一个元素,你可以使用下标运算符,而不必担心解除引用。

这样做:

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