Another.Chemist
Another.Chemist

Reputation: 2559

strcmp() not comparing

Hello everybody, I'm a newbie and I'm doing a code that the principal aim is to print a number if two strings are equal. First string is obtained from a file and the second one is the string to be compared with.

The code:

int main()
{
char *string[2];
FILE *stream;
stream = fopen("REL","r");
if( (stream = fopen("REL","r")) == NULL)
{  
    printf("Can't open %s\n","REL");
    exit(1);
}
for(int i=0;i<92;i++)
{
    fscanf(stream,"%s",&string);
    if( strcmp("20", *string) == 0 )
    {
        printf("%d",20);
    }
}
fclose(stream);
}

and... when I tested on shell, it promp to me:

~/CM$ ./file2 
Segmentation fault (core dumped)

I might be doing a silly mistake. But, as a newbie, I cannot figure out whats is going wrong with the script.

Upvotes: 1

Views: 493

Answers (2)

hmjd
hmjd

Reputation: 122011

string is an unitialised array of 2 char*. The fscanf is attempting to write to memory where is should not. Declare string as an array of char:

char string[256];

and:

fscanf(stream, "%255s", string); /* Limit number of
                                    chars read to prevent buffer overrun. */

Upvotes: 3

Marcos
Marcos

Reputation: 4653

Try this:

char string[128];
fscanf(stream, "%s", string);

and then:

if (!strcmp("20", string)) {
    /* The strings are equals */
}

Upvotes: 1

Related Questions