Example 1 — Measure and uppercase a string
A pointer walks the characters until the terminator.
#include <stdio.h>
#include <ctype.h>
static size_t my_len(const char *s) {
const char *p = s;
while (*p) p++;
return (size_t)(p - s);
}
int main(void) {
char word[] = "hello";
printf("%s has %zu chars\n", word, my_len(word));
for (char *p = word; *p; p++) {
*p = (char)toupper((unsigned char)*p);
}
printf("%s\n", word);
return 0;
} How It Works
my_lenadvancespuntil it hits'\0'and subtracts the start.wordis a writable array, so uppercase edits are legal.- Casting to
unsigned charkeepstouppersafe for all values.
