【发布时间】:2016-10-19 13:39:11
【问题描述】:
我想向 json->setInformation 发送一个结构,但是当我尝试复制结构内的数组时,我的程序崩溃了。其余数据都还好,只是导致崩溃发生的数组。
info = data->getInformation();
json->setInformation(info);
getInformation 返回一个我可以在main.cpp 中读取的结构
当我尝试将此结构发送到 setInformation 时,它崩溃了......
information.h 包含我的结构
struct information{
String location;
String protocol;
uint8_t groupID;
uint8_t* data;
information& operator=(const struct information& that){
location = that.location;
protocol = that.protocol;
groupID = that.groupID;
for (int i = 0; i < 9; ++i){
data[i] = that.data[i];
}
return *this;
}
};
json.cpp
void JSON::setInformation(information data){
info->location = data.location;
info->protocol = data.protocol;
info->groupID = data.groupID;
// for (int i = 0; i < 9; ++i){
// info->data[i] = data.data[i];
// }
// Serial.print("after JSON: ");
// Serial.println(info->data[0]);
}
这段代码工作正常,但是当我取消注释应该复制数组的 for lop 时,它会崩溃
【问题讨论】:
-
你的结构没有数组。它有一个指针。想想指针指向什么。
-
您究竟在哪里设置
data字段以指向适当大小的有效内存块? -
考虑发布更多代码(特别是关于 uint8_t 数组分配/释放)。
-
顺便说一句,阅读您的代码,看起来您不妨声明
uint8_t data[9],并在operator=函数中,只需执行return *this = that(顺便说一句,这意味着您不甚至需要这个函数,因为语言标准已经支持结构赋值)。
标签: c++ arrays function struct