0

我有一个类属性,它是一个字符串数组(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会使其无法使用?

4

2 回答 2

2

为什么使用 memset 将字符串数组设置为 0 会使其无法使用?

因为您正在删除字符串类中保存的值,所以用 0 覆盖它们。Astd::string有指向它存储字符串、字符计数信息等的内存的指针。如果你 memset() 将所有这些都设置为 0,它将无法工作。

于 2015-11-23T19:49:11.623 回答
0

您来自错误的默认位置。将内存“归零”是有意义(甚至有用)操作的类型是特殊的;你不应该期望做这样的事情会带来任何好处,除非该类型是专门设计用于处理它的。

于 2015-11-24T14:37:03.923 回答