Walle
Walle

Reputation: 317

Compare 2 strings in C

I'm testing a small program which basically compares whether 2 input strings are identical (as strcmp does). However I keep getting result saying 2 strings are different no matter what. If someone could spot out some mistakes I'd appreciate

int comp(char str1[], char str2[]) {
    int i = 0;
    while (str1[i] == str2[i]) {
        if (str1[i] == '\0' || str2[i] == '\0')
            break;
        i++;
    }
    if (str1[i] == '\0' && str2[i] == '\0')
        return 0;
    else
        return -1;
}


int main(int argc, char * * argv) {
    int cmp;
    char str1[1000], str2[1000];
    cmp = comp(str1, str2);
    if (cmp == 0)
        printf("The two strings are identical.\n");
    else
        printf("The two strings are different.\n");
    return 0;
}

Upvotes: 3

Views: 206

Answers (2)

user3629249
user3629249

Reputation: 16540

here is one implementation, using the command line parameters.

#include <stdio.h>
#include <stdlib.h>

int comp(char str1[], char str2[])
{
    int i = 0;
    while (str1[i] == str2[i])
    {
        if (str1[i] == '\0' || str2[i] == '\0')
            break;
        i++;
    }

    if (str1[i] == '\0' && str2[i] == '\0')
        return 0;
    else
        return -1;
}


int main(int argc, char * * argv)
{
    if( 3 != argc )
    {
        printf( "USAGE: %s, firstString secondString\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // implied else, correct number of parameters

    if ( !comp( argv[1], argv[2]) )
        printf("The two strings are identical.\n");
    else
        printf("The two strings are different.\n");
    return 0;
}

Upvotes: 0

Shoe
Shoe

Reputation: 76240

Your function works just fine. The only problem is that your two character arrays are not initialized and that causes Undefined Behavior.

Upvotes: 8

Related Questions