0

I'm programming in C. I have loaded a 2d array with words. It is called dictionary[][]. I am trying to use strstr to find out how many of the words have a substring in them of "struct". Here is the code. In my function count_matches I try to iterate through dictionary using the strstr function to compare. It always returns null so I never get to ++matchcount. Any ideas why?

Here is the function. inp is "struct" dictionary is the 2d array and n is the number of lines in the array (I.e. how many words are in the array).

int count_matches(char *inp, char dictionary[MAX_LINES][MAX_LEN], int n)
{
int matchcount = 0;
int i;

for (i=0; i < n; ++i)
    {
        if (strstr(dictionary[i], inp) !=NULL)
            {
                ++matchcount;
            }
    }
return matchcount;
}
Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
CJF
  • 1

1 Answers1

0

I don't see your problem in the given code snippet.

Think about the following:

  1. Did you mix up MAX_LINES and MAX_LEN?

  2. Is the inp really equal to "struct"?

  3. Did you load the dictionary with at least one word that has the substring "struct"?

Show the code where you make the call to this function if the problem persists.

For example, this works fine:

int main()
{
    char dictionary[MAX_LINES][MAX_LEN] = {"hello", "hihello", "bye", "Hello"};
    int output = count_matches("hello", dictionary, 4);
    printf("%d", output); // Output is 2 as expected
    return 0;
}

By the way, you can also consider making the following changes to your code:

  1. MAX_WORDS is more readable than MAX_LINES

  2. You do not necessarily have to write != NULL inside that condition

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53