[英]String array unusable after setting it to 0 using memset
我有一個類屬性,它是一個字符串數組( 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));
刪除任何先前的值之前正在清洗數組memset(command, 0, sizeof(command));
。 這是引起問題的原因。 現在,我對數組中的每個項目使用clear
函數,如下所示。 這解決了執行問題。
for (int i = 0; i < sizeof(command)/sizeof(*command); i++){
command[i].clear();
}
問題:為什么使用memset
將字符串數組設置為0使其不可用?
為什么使用memset將字符串數組設置為0使其不可用?
因為您要消除字符串類中保存的值,所以將所有值都覆蓋為0。 std::string
具有指向存儲字符串,字符計數信息等的內存的指針。如果將memset()都設置為0,則它將無法正常工作。
您來自錯誤的默認位置。 “清零”內存是有意義的(甚至是有用的 )操作的類型是特殊的; 您不應期望這樣做會帶來任何好處,除非該類型是專門為此設計的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.