簡體   English   中英

使用memset將其設置為0后,字符串數組不可用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM