C++結構體內存分配問題


=========20190713  update================

結構體信息如下

struct picInfo{
    std::string path;
    unsigned int width;
    unsigned int height;
    unsigned int extra;    
};

struct areaPos{
    unsigned int width;
    unsigned int height;  
};

struct DisplayInfo{
    picInfo carPicInfo;
    unsigned int distancePicNum;
    picInfo* distancePicInfo;
    unsigned int frontRadarNum;
    unsigned int rightRadarNum;
    unsigned int rearRadarNum;
    unsigned int leftRadarNum;
    unsigned long distanceScale;
    areaPos envAreaPos;
    areaPos videoAreaPos;
};

目前需要動態申請一個DisplayInfo空間

使用如下方式申請內存

distancePicInfo = (picInfo* )malloc(10*sizeof(picInfo));

然后對distancePicInfo進行賦值操作

    for(auto && info:distInfoNode){
       distancePicInfo[distPicCnt].path= distInfo.path;
       distancePicInfo[distPicCnt].width= distInfo.width;
       distancePicInfo[distPicCnt].height= distInfo.height;
       distancePicInfo[distPicCnt].extra= distInfo.extra;
       distPicCnt++;    
    }

運行報錯了,說引用了非法地址,可以得出申請內存肯定失敗了的結論

修改結構體聲明如下,即可解決

struct picInfo{
    const char* path;
    unsigned int width;
    unsigned int height;
    unsigned int extra;    
};

struct areaPos{
    unsigned int width;
    unsigned int height;  
};

struct DisplayInfo{
    picInfo carPicInfo;
    unsigned int distancePicNum;
    picInfo* distancePicInfo;
    unsigned int frontRadarNum;
    unsigned int rightRadarNum;
    unsigned int rearRadarNum;
    unsigned int leftRadarNum;
    unsigned long distanceScale;
    areaPos envAreaPos;
    areaPos videoAreaPos;
};

 

 先記錄下,后面有時間再研究


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM