"Buck Rogers" <> writes:
> Hi guys, newbie here.
>
> I am trying to write a program which counts the number of characters
> in two strings, then prints the number, and states which string is longer.
>
> For some reason, my program gives an incorrect number of characters
> in each string(1 character less), and I have no idea why.
>
> Can somebody pls explain this?
>
> Thanks in advance.
>
> Buck.
> .
> =================
>
> #include <stdio.h>
>
> char string_one[] = "string one";
> char string_two[] = "is this string longer?";
>
> int main ( void )
> {
> int ctr, ctr1, ctr2;
>
> for( ctr = 0; string_one[ctr] != NULL; ctr++ )
The comparison against NULL is strange. NULL is meant to represent a
null pointer constant, not some type of character. If NULL is
defined as (void*)0, then string_one[ctr] will be converted to a
void* before the comparison, which could result in a trap
representation; or conceivably even a false positive for your
comparison. NULL is not meant to represent the "null character
terminator", which is simply a zero-valued integer. Use one of:
string_one[ctr] != 0
string_one[ctr] != '\0'
(Both have exactly the same meaning, but I find the first
slightly clearer).
> {
> ctr1 = ctr;
You know, you could avoid this assignment if you just used ctr1
instead of ctr within the for clauses... At any rate, assigning
to ctr1 on every iteration is just wasted cycles: and it also
accounts for the error in your algorithm. Because when ctr *is*
the right value for the length, the body of the for-loop never
gets executed, since (string_one[ctr] != '\0') is true.
> }
Why did you feel the need to write this yourself? The standard
library already provides strlen() in string.h.
>
> for( ctr = 0; string_two[ctr] != NULL; ctr++ )
> {
> ctr2 = ctr;
> }
Same comments as above.
>
> printf(" \nstring_one has %d characters\n ", ctr1);
> printf(" \nstring_two has %d characters\n ", ctr2);
>
> if( ctr1 < ctr2 )
> {
> printf( "The longer string is string_two" );
> }
>
> else
> printf( "\nstring_one is longer" );
>
> return 0;
> }
Both of the conditionally executed printf() statements above
don't end with a line-terminating '\n', as they should. I find
that it's much easier to realize this sort of problem if you make
the general habit of putting your '\n's at the *end* of the
strings you output, rather than at the beginning (I've *never*
understood why so many beginners do this. Is there a book
somewhere that advocates this?).
HAND.
--
Micah J. Cowan