我有一个类属性,它是一个字符串数组(std::string command[10]
)。当我为其分配一些字符串值时,它会停止程序执行。正如您在下面看到的,我有一个字符串变量tempCommandStr
,我分配给我的属性。我不知道错误可能是什么,但我在赋值后的 print 语句从未执行过,而前面的语句是。
//Declared in class header
std::string command[10];
// Part of function which is causing problem.
string tempCommandStr(commandCharArray);
printf("%s\n", tempCommandStr.c_str()); // Prints fine.
this->command[i] = tempCommandStr; // Something goes wrong here. i is set to some correct value, i.e. not out of range.
printf("%s\n", this->command[i].c_str()); // Never prints. Also program stops responding.
// I noticed that getting any value from the array also stops the execution.
// Just the following statement would stop the program too.
printf("%s\n", this->command[i].c_str());
不仅仅是这个属性,我还有另一个数组也有同样的问题。这可能是什么原因造成的?实际上出了什么问题(查看编辑)?还有另一种更好的方法吗?
我在 MBED 上运行程序,所以我限制了调试选项。
编辑:
我发现了问题,在使用删除任何以前的值之前,我正在清理数组memset(command, 0, sizeof(command));
。这是造成问题的原因。现在我clear
在数组中的每个项目上使用该函数,如下所示。这解决了执行问题。
for (int i = 0; i < sizeof(command)/sizeof(*command); i++){
command[i].clear();
}
问题:为什么将字符串数组设置为 0 usingmemset
会使其无法使用?