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; };
先记录下,后面有时间再研究
作者:pngcui
博客园:http://www.cnblogs.com/pngcui/
github:https://github.com/pngcui
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明。