Einārs Ozols Einārs Ozols - 17 days ago 5
C Question

Compare tokens with strcmp

I need to compare tokens.
I need to know two tokens which are equal.
This is my code. And something is going wrong when comparing- compilator just crashes.
Can you help me to find error?

int main()
{
int i=0;
char* words[200];
char text[200];

printf("Enter one sentence \n ");
gets(text);
char *word = strtok(text, " ");

while(word!=0)
{
words[i++] = strdup(word);
printf("[%s]\n", word);
word=strtok(NULL, " ,.!?");
}






for (k=0; k<199; k++)
{
for (j=k+1; j<200; j++)
{
if (strcmp(words[k],words[j])==0)
{
printf("Equal words are %s",words);
}
else
{
printf("In this sentence aren't equal words");
}
}

}
getch();
return 0;

Answer
  1. In your for loops you iterate until 200, not until the max number of entered words (i) is reached.

  2. There is no guarantee which value the elements of an uninitialized array will have at runtime. They might be 0, but also might be any other random numbers. Which means, that doing strcmp with any array element beyond the number of entered words will result in undefined behavior.

Do your nested for-loop like this:

for (k=0; k < i-1; k++)
{
  for (j=k+1; j < i; j++)
  { 
    ...
  }
}
Comments