char buffers in Arduino
Fixed buffers avoid String's heap churn on a 2 KB board.
// Fixed char buffers avoid String's heap churn on a 2 KB board.
char label[16];
int batch = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
batch++;
// snprintf formats safely into the buffer, never past it.
snprintf(label, sizeof(label), "batch-%03d", batch);
Serial.print(label);
Serial.print(" len=");
Serial.println(strlen(label));
delay(1000);
}
How it works
char label[16]reserves the space once, globally.snprintfformats into it and never writes past the end.strlenconfirms what actually landed.
Keywords and builtins used here
Serialbeginchardelayintloopprintprintlnsetupsizeofvoid
The run, in numbers
- Lines
- 17
- Characters to type
- 359
- Tokens
- 83
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 77 seconds.
Step 1 of 3 in Data, step 19 of 27 in Language basics.