Pregunta

I wanted to write a program to check which string has a greater length without using string functions. I tried to get the two strings as input using gets() but my program keeps on crashing. Please help! Thanks!

Here's my code:

#include <stdio.h>
int l1,l2;
char *st1,*st2;
void accept()
{
    gets(st1);
    gets(st2);
}
void length()
{
    int i = 0;
    while (st1[i] != '\0')
    {
        l1++; i++;
    }
    i = 0;
    while (st2[i] != '\0')
    {
        l1++; i++;
    }

}
int main()
{
    accept();
    length();
    if (l1 > l2)
        printf("String #1 is greater in length.\n");
    else
        printf("String #2 is greater in length.\n");
}
¿Fue útil?

Solución

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.

Otros consejos

use l2 in the second while loop,

    l1=0;
    while (st1[l1] != '\0')
    {
        l1++;
    }
    l2 = 0;
    while (st2[l2] != '\0')
    {
        l2++;
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top