gpt4 book ai didi

c++ - 无法使用指向其他结构的嵌套指针初始化结构

转载 作者:太空狗 更新时间:2023-10-29 20:17:08 24 4
gpt4 key购买 nike

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

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) 的一个实例,但是无法编译...因为它没有类型定义(它表示 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;
//...

关于c++ - 无法使用指向其他结构的嵌套指针初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7615369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com