user119949
user119949

Reputation: 101

Output mistake in array

int BruteForceStringMatch(char Text[], char Pattern[]){

    int TextSize = sizeof(Text) / sizeof(Text[0]); //get size of arrays
    int PatternSize = sizeof(Pattern) / sizeof(Pattern[0]);
    int i;
    for(i = 0; i++; i < TextSize - PatternSize){
        int j = 0;
        while(j < PatternSize && Pattern[j] == Text[i + j]){
            j = j + 1;
        }
        if(j = PatternSize){
            return i;
        }
    }
    return -1;
}

int main() {
    char x [] = "if" ;
    char y [] = "aslifee";

    int c = BruteForceStringMatch(y,x);
    printf("%d ",c);

    getchar();       
}

Hi everyone, I want to match text and pattern by using BruteForceStringMatch function but I get output -1 from computer. Here I should get 3 (because fourth element is matching) but why am I getting -1 which means there is no matching?

Upvotes: 0

Views: 51

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726669

Here is what is wrong:

int TextSize = sizeof(Text)/sizeof(Text[0]); //get size of arrays

This does not give you the size of the array, because C passes arrays to functions as if they were pointers. The size of the array is stripped from it, so sizeof returns the size of the pointer.

Use strlen instead:

int TextSize = strlen(Text);

Same goes for the pattern size.

Note: I assume that you are doing this as a learning exercise, because C standard library supplies a function for finding strings within strings.

Upvotes: 1

Related Questions