| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | testlen.c |
#include
#include
int main(void)
{
char *string = "this is a string";
printf("length is %d, stdlib is
%d\n",lenstr(string),strlen(string));
return 0;
}
int lenstr(char *s)
{
int n=0;
while(*s++) n++;
return n;
}
This is exactly the loop I used, and so did Kernighan and Ritchie.
Compile it, and it will return 16 and 16 correctly.
Sorry to be so pedantic, Jasen, but both you and Darin are reading much
too much into a simple counting loop, and extrapolating nonsense from your
imaginings.
If you USE s or *s in the body of the loop, that is quite a different
matter. Then the last thing in the body of the loop should be the increment
of s to determine the exact order of execution. The elision in *s++ would
not work in that case, because it would reference a different set. E.g. to
output the contents of the string the loop would have to be something
like:-
while (*s != '\0') { putc((int)*s,(FILE *)stdout); s++);
This would normally be elided to:-
while(*s) {putc(*s,stdout); s++;};
or even:-
while(*s) putc(*s++, stdout);
To dereference (s-1) [i.e. *(s-1)] is an error.
Are we clear now?
Best Wishes,
Bill.
---
* Origin: Escan BBS (2:25/200)SEEN-BY: 633/267 270 @PATH: 25/200 108 252/110 250/501 140/1 106/2000 633/267 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.