lundi 14 mai 2018

initializing a fixed C array member struct

I have a very simple POD struct containing an array member shown below. I am having problems initializing the fixed length array member memberArray with a reference fixed length array parameter const uint32_t(&rArrayArg)[22]. I will not have access to the standard library in the final target environment.

The member initializer memberArray{*rArrayArg} only copies the first entry from the rArrayArg arg. In order to see the complete array, I need to memcpy or (as shown here) std::copy in the body of the constructor.

I have another POD struct that takes a 2 dimensional fixed length array const uint32_t(&rArrayArg)[4][5] which will be used to initialize a corresponding 2d member, so a general solution for the member initialization syntax would be preferred.

struct TestStruct {
    explicit TestStruct(
        const uint32_t(&rArrayArg)[22])
        : memberArray{*rArrayArg}
    {
        //std::copy(std::cbegin(rArrayArg), std::cend(rArrayArg), memberArray);
    }

    uint32_t memberArray[22];

    // this stream helper is only present for debugging purposes
    // in the actual target environment, I will not have access to std:: 
    friend std::ostream& operator<<(std::ostream& os, const TestStruct& rhs) {
        os << "TestStruct: ";
        for (auto next : rhs.memberArray) {
            os << next << ",";
        }
        return os;
    }
};

The following live demo shows the result of passing a partially populated fixed array parameter uint32_t fixedLenArg[22] = {1,2,3,4,5,6}; to the explicit constructor. Printing the results shows:

TestStruct: 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

so clearly only the first parameter is being copied. If I uncomment the std::copy in the body of the constructor (this is debug as I do not have access to std::copy in the final environment) I get the following:

TestStruct: 1,2,3,4,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

Aucun commentaire:

Enregistrer un commentaire