user2646276
user2646276

Reputation:

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. I wish to split the bitset into an array of 14 bytes of uint8_t and return this array to the main function. I have written a for loop to do this. 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???

thanks.

edited to take out another error my compiler pointed out once I had solved this error.

Upvotes: 0

Views: 505

Answers (1)

Tony The Lion
Tony The Lion

Reputation: 63250

Because you have a pointer, you don't need to dereference and use operator[] on the array. 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.  

Upvotes: 1

Related Questions