0

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.

6
  • (byteArray+j) is pointer, byteArray[j] is element at that position (i.e. byteArray[j] the same as *(byteArray+j)). Commented Aug 22, 2013 at 12:28
  • Ew, don't do this. Return std::vector<uint8_t>. Commented Aug 22, 2013 at 12:29
  • Does this even compile? return byteArray[j]; Commented Aug 22, 2013 at 12:31
  • Welcome to the wonderful world of C arrays. It doesn't get any less confusing. Commented Aug 22, 2013 at 12:31
  • Martinho - I want to return a pointer to an array because that is what a predifined function I am using requires. Dasblinkenlight - You're right, I hadn't spotted that mistake until I fixed the first error. Editted it out. Commented Aug 22, 2013 at 12:39

1 Answer 1

1

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.  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.