Arrays and Strings
String Length
A string scan usually stops when it reaches the null terminator.
scan
A scan moves one character at a time through an array.
terminator check
Stopping at `'\0'` prevents hidden buffer contents from being treated as text.
String Length
string_length.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
char text[5] = {'h', 'i', '\0', 'x', '\0'};
int stopAtNull = 1;
int length = 0;
while (length < 5) {
if (stopAtNull && text[length] == '\0') {
break;
}
length++;
}
printf("length=%d\n", length);
return 0;
}
#include <stdio.h>
int main(void) {
char text[5] = {'h', 'i', '\0', 'x', '\0'};
int stopAtNull = 0;
int length = 0;
while (length < 5) {
if (stopAtNull && text[length] == '\0') {
break;
}
length++;
}
printf("length=%d\n", length);
return 0;
}
text ← hi, stopAtNull ← 1, length ← 0
3int main(void) {4 char text→ hi[5] = {'h', 'i', '\0', 'x', '\0'};5 int stopAtNull→ 1 = 1; //@stopAtNull=06 int length→ 0 = 0;length ← 1
pass 1 of 38while (length0 < 5) {9 if (stopAtNull && text[length] == '\0') {10 break;11 }12 length→ 1++;13}All 3 passes — pass 1 is the card above pass stopAtNulltext[length]length1 — — 0 → 1 2 — — 1 → 2 3 1