zoukankan      html  css  js  c++  java
  • 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;
    };

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

  • 相关阅读:
    Oracle-启动和关闭oracle的归档(ARCHIVELOG)模式
    Linux-数据表示方式
    Linux-21-30
    linux-1-10
    自律
    jenkins-修改系统时间
    jenkins-通过ssh username with private key配置节点服务器
    jenkins-slave开机自动启动
    mongodb-mongo使用
    mongodb-centos76yum安装mongodb
  • 原文地址:https://www.cnblogs.com/pngcui/p/11180788.html
Copyright © 2011-2022 走看看