you have not allocated space to st1
or st2
nor have you initialized them... so they are both pointing to some unknown place in memory. Try...
char st1[1024];
char st2[1024];
That said, realize that gets
is inherently unsafe as it is subject to buffer overrun attack; there's nothing to stop someone from entering a string longer than 1024 and crashing your program.
You can also greatly simplify the length() function as follows...
void length()
{
for (l1 = 0; st1[l1] != '\0'; l1++ );
for (l2 = 0; st2[l2] != '\0'; l2++ );
}
Expanding on this and your question about what's an alternative to gets()
, the answer is to use something like fgets()
-- for example...
int main( int argc, char** argv )
{
if( fgets( st1, sizeof( st1 ), stdin ) != NULL )
{
if( fgets( st2, sizeof( st2 ), stdin ) != NULL )
{
length();
if (l1 > l2) printf("String #1 is greater in length.\n");
else if (l2 > l1) printf("String #2 is greater in length.\n");
else printf( "Both strings are the same length.\n" );
}
else printf( "could not read second string\n" );
}
else printf( "could not read first string\n" );
return( 0 );
}
In this case, fgets()
will not allow the user to overflow st1
or st2
and it will ensure they are always null terminated strings.