Monday, October 19, 2009

Pointers - Example 2

To find the length of the string without using strlen:
Strings are terminated by a NULL character. So scan the string character-by-character until you hit the null character in memory. The number of characters traversed until you reach the NULL character is the string-length.

#include <stdio.h>
int main() {
char* name = "Leprechaun";
int length = 0;
char *p = name;
//easy way: use built-in function. include string.h for this.
//length = strlen(name);
//using pointers
for(;*name!='\0';name++) {
length++;
}
printf("Length of %s is %d\n", p, length);
return 0;
}

No comments:

Post a Comment