ArduinoのSketch(スケッチ)で、変数や配列のバイト数を確認するsizeofについて解説します。
sizeofは変数や配列のバイト数を返し、書式は次の通りです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
//Arduino Sketch Example: sizeof //Date: 2015.1.12 //Edited and Modified by: easy labo //Original Source: Arduino Reference (http://arduino.cc/en/Reference/HomePage) //Syntax sizeof(variable) //variable: any variable type or array (e.g. int, float, byte) //Example-1 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); // slow down the program } //Example-2 for (i = 0; i < (sizeof(myInts)/sizeof(int)) - 1; i++) { // do something with myInts[i] } |
Creative Commons Attribution-ShareAlike 3.0 License (CC BY-SA 3.0)
“Arduino Reference:sizeof” by Arduino Team, used under CC BY-SA 3.0/ easy labo made some changes and comments to the original
上のExample-1では、文章を1文字ずつプリントアウトしています。また、Example-2では、sizeof(myInts)をsizeof(int)で割ってmyIntsの配列数を、を取得しています。
Sponsored Link