sizeof
描述
運算子 sizeof
可以根據變數型態回傳一個單位為 byte 的數字,或者一個陣列所占用的 byte 數。
語法
sizeof(variable)
參數
variable
: 任意型態的變數或陣列 (例如: int, float, byte)
範例
運算子 sizeof
對於處理陣列 (例如:字串) 是相當的方便的,他可以讀出陣列的大小而不會破壞程式的其它部分。
這個程式可以一次一個字元的印出文字字串,嘗試去改變文字片段。
char myStr[] = "this is a test"; int i; void setup(){ Serial.begin(9600); } void loop() { for (i = 0; i < sizeof(myStr) - 1; i++){ Serial.print(i, DEC); Serial.print(" = "); Serial.write(myStr[i]); Serial.println(); } delay(5000); // 放慢程式的運作 }
注意 sizeof
回傳的 byte 數,在 for 迴圈裡面若使用 sizeof 去取得較大變數型別 (如 int) 的陣列元素個數時,將會像下面這樣;另外,也要注意到字串嚴謹的規則,結尾會有空字元 \0 (ASCII 的值是 0)。
for (i = 0; i < (sizeof(myInts)/sizeof(int)) - 1; i++) { // 運用 myInts[i] 做一些事情 }
本頁由熱血青年 LBU 譯自英文版。
The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.