sizeof()

[Utilities]

描述

The sizeof operator returns the number of bytes in a variable type, or the number of bytes occupied by an array.

語法

sizeof(variable)

參數

variable: The thing to get the size of. Allowed data types: any variable type or array (e.g. intfloatbyte).

回傳

The number of bytes in a variable or bytes occupied in an array.

Example Code

The sizeof operator is useful for dealing with arrays (such as strings) where it is convenient to be able to change the size of the array without breaking other parts of the program.

This program prints out a text string one character at a time. Try changing the text phrase.

char myStr[] = "this is a test";

void setup() {
  Serial.begin(9600);
}

void loop() {
  for (byte i = 0; i < sizeof(myStr) - 1; i++) {
    Serial.print(i, DEC);
    Serial.print(" = ");
    Serial.write(myStr[i]);
    Serial.println();
  }
  delay(5000);  // slow down the program
}

Tip

Note that sizeof returns the total number of bytes. So for arrays of larger variable types such as ints, the for loop would look something like this.

int myValues[] = {123, 456, 789};

// this for loop works correctly with an array of any type or size
for (byte i = 0; i < (sizeof(myValues) / sizeof(myValues[0])); i++) {
  // do something with myValues[i]
}

Note that a properly formatted string ends with the NULL symbol, which has ASCII value 0.


語法參考主頁面

86Duino 參考的文本是根據 Creative Commons Attribution-ShareAlike 3.0 License,部分文本是從 the Arduino reference 修改的。 參考中的代碼示例已發佈到公共領域。

發表評論

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

Scroll to Top