加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:37:33 所属栏目:百科 来源:网络整理
导读:我正在使用定义此结构的第三方库: typedef struct{ unsigned short nbDetectors; //! structure of detector status struct DetectorStatus { unsigned int lastError; // last detector internal error float temperature; // detector temperature detect
我正在使用定义此结构的第三方库:

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;
//...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读