[英]Can't initialize struct with nested pointers to other structs
我正在使用定義此結構的第三方庫:
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
類型)? 所以我很難過......我如何填充結構?
你可以重視它:
HardwareStatus status = {};
如果要實例化BatteryStatus
,可以通過完全限定名稱來實現:
HardwareStatus::DetectorStatus::EnergyStatus::BatteryStatus bs;
如果你想把所有東西放在堆棧上,你應該這樣做:
// 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;
//...
你嘗試將結構設置為0嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.