-1

I have two struct arrays and a nested for loop. There are words that are identical in the two arrays, but strcasestr is not detecting them. I used strcasestr to also find substrings within words that are identical.

Here's a snippet of my code:

for(int itr = 0; itr < arrayItr; itr++)
{
    for(int itr2 = 0; itr2 < arrayItr2; itr2++)
    {
        if(strcasestr(termsArraypast[itr].term, termsArrayTerms[itr2].term) > 0)
        {
            printf("%d %d %s\n", termsArraypast[itr].charDistance, termsArraypast[itr].termDistance, termsArraypast[itr].term);
        }
    }
}

Please know that all of these variables have already been declared in my program. I've just been on this portion for hours and can't figure it out. Thanks.

IC2D
  • 471
  • 4
  • 11
  • 22
  • The condition is wrong. The `strcasestr` function returns a pointer to the beginning of the substring, or `NULL` if the string is not found. Whole technically non-null is larger than zero, you should still compare against `NULL`. – Some programmer dude Nov 05 '13 at 05:56
  • As for the problem, what are the contents of the two strings you pass to the function? – Some programmer dude Nov 05 '13 at 05:56

1 Answers1

0

char *strcasestr(const char *haystack, const char *needle);

return a pointer to the beginning of the substring or null if the string is not found

So it will return a pointer value not an integer which may be outside of integer range.

And you are comparing it with greater than 0 . That is wrong , You could just check for not zero.

eg: program

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

  int main()
  {
char arr1[10];
char arr2[10];
int ret;
strcpy(arr1,"foobar");
strcpy(arr2,"foobar");
printf("arr1 %s\n",arr1);
printf("arr2 %s\n",arr2);

ret= strcasestr(arr1,arr2) ;

printf("ret %d ret %p \n",ret,ret);
if(strcasestr(arr1,arr2) >0)
{
    printf("sub found\n");
}
    if(strcasestr(arr1,arr2) != 0)
     printf("substring found for not null check \n" );      
 }

o/p

arr1 foobar
arr2 foobar
ret -1073787886 ret 0xbfff4c12 
substring found for not null check 
Knight71
  • 2,927
  • 5
  • 37
  • 63