為Arduino中的字串操作預留記憶體


在程式執行過程中,字串可能會發生動態長度變化。

如果你想確保始終有足夠的記憶體可用於你的字串,則可以使用reserve()函式預留一些記憶體。

語法

String1.reserve(n_bytes);

其中String1 是要預留記憶體的字串,n_bytes (無符號整數)是要在記憶體中預留的位元組數。

示例

String s1 = "Hello";

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   s1.reserve(20);
   s1 = s1+" World!";
   Serial.println(s1);
   s1 = s1+" I'm now trying to exceed the reserved memory";
   Serial.println(s1);
}

void loop() {
   // put your main code here, to run repeatedly:
}

輸出

序列監視器輸出如下所示 -

如你所見,即使我們超過了預留的記憶體,也沒有出現任何後果,因為有足夠的可用記憶體。此函式僅有助於為字串預留一些記憶體,以便我們不會在執行時面臨短缺,特別是在執行繁重程式碼時。

更新日期: 29-五月-2021

723次瀏覽

開始你的職業生涯

透過完成課程來獲取認證

開始
廣告