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";
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);
}
Notes and Warnings
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};
for (i = 0; i < (sizeof(myValues) / sizeof(myValues[0])); i++) {
}
Note that a properly formatted string ends with the NULL symbol, which has ASCII value 0.