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.