c – 无法使用嵌套指向其他结构的初始化struct

我正在使用定义此结构的第三方库:

typedef struct
{
    unsigned short nbDetectors;
    //! structure of detector status
    struct DetectorStatus
    {
        unsigned int lastError;         //< last detector internal error
        float temperature;              //< detector temperature
        detector_state state;           //< detector state
        unsigned short mode;            //< detector mode

        struct EnergyStatus
        {
            power_source powerSource;           //< front-end power source
            frontend_position frontendPosition; //< front-end position relative to the docking station

            struct BatteryStatus
            {
                bool present;                   //< battery present or not in the detector
                unsigned short charge;          //< charge level of the battery (in %)
                float voltageLevel;             //< battery voltage level
                float temperature;              //< temperature of the battery
                unsigned short chargeCycles;    //< number of charge/discharge cycles
                unsigned short accuracy;        //< Expected accuracy for charge level (in %)
                bool needCalibration;

            } batteryStatus;

        } * energyStatus;

        struct GridStatus
        {
            detector_grid grid;

        } * gridStatus;

    } * detectorStatus;

} HardwareStatus;

库使用此结构作为其回调之一传递的数据.所以它是填满它的库,我只是阅读它.到现在为止还挺好.

但是现在我正在为这个库处理的设备编写一个模拟器,所以现在我必须填写其中一个结构,我无法正确使用它.

我试过这个:

HardwareStatus status;
status.detectorStatus->temperature = 20 + rand() % 10;
e.data = &status;
m_pContext->EventCallback( EVT_HARDWARE_STATUS, &e );

当我编译时,我得到了:

warning C4700: uninitialized local variable 'status' used

然后我意识到……结构中的指针指向垃圾,很好地捕获Visual Studio!那么我试着从声明一个最里面的结构(BatteryStatus)的实例开始,但那不会编译…因为它不是typedef(它说没有定义BatteryStatus类型)?所以我很难过……我如何填充结构?

解决方法:

如果你想把所有东西放在堆栈上,你应该这样做:

// Getting structs on the stack initialized to zero
HardwareStatus status = { 0 };
HardwareStatus::DetectorStatus detectorStatus = { 0 };
HardwareStatus::DetectorStatus::EnergyStatus energyStatus = { 0 };
HardwareStatus::DetectorStatus::GridStatus gridStatus = { 0 };

// "Linking" structs
detectorStatus.energyStatus = &energyStatus;
detectorStatus.gridStatus = &gridStatus;
status.detectorStatus = &detectorStatus;

// Now you can fill and use them
status.detectorStatus->temperature = 20 + 3 % 10;
//...
上一篇:javascript – 为什么我的嵌套if和else语句不起作用?


下一篇:C嵌套类中的“this”关键字