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;
};

 

 先记录下,后面有时间再研究

posted @ 2019-07-13 15:28  某某璀  阅读(2259)  评论(0编辑  收藏  举报
levels of contents