Reputation: 155
I need to store tokens into an array. And then i want to find equal tokens in sentence.
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=malloc(strlen(word)+1);
strcpy(words[i++], word);
printf("[%s]\n", word);
word=strtok(NULL, " ,.!?");
}
getch();
return 0;
}
I don't know why is this erorr- 22 incompatible types in assignment of void* to char*[200]' And if i change words to words[i]=malloc..... got error 22 invalid conversion from void* to char*'
And then i want to know how from this array i can compare these tokens with strcmp. This is my try but looks like not working.
for (k=0; k<199; k++)
{
for (j=k+1; j<200; j++)
{
if (strcmp(words[k],words[j])==0)
{
printf("equal words are %d",words);
}
else
{
printf("In this sentence aren't equal words");
}
}
}
Upvotes: 1
Views: 993
Reputation: 1576
char * words[200]
is a 200-element array of char *
s.
Arrays are static, so words=malloc(strlen(word)+1);
doesn't make sense. words is an array of pointers, but malloc
returns a void *
.
I think what you want is to have a variable to use as an iterator - words[i]
instead of just words
.
If changing to words[i] = malloc(strlen(word)+1);
gives you an invalid conversion error, you can try casting, though you shouldn't have to, since malloc
returns a void*
. To cast, use words[i] = (char*) malloc(strlen(word) + 1);
. The (char*)
tells the compiler that even though it looks like you're doing an invalid conversion, you know what you're doing.
Also, for the second part that attempts to find matching strings, I think you mean something like this for the first printf:
printf("Equal words are %d, %d: %s\n", j, k, words[j]);
Upvotes: 1
Reputation: 121397
Change
words=malloc(strlen(word)+1);
to
words[i]=malloc(strlen(word)+1);
Currently, you are assigning the malloc'ed value to the array itself, you rather intended to assign it to an element of the array.
If you have strdup() (a posix function, not in standard C), then you can use it instead of malloc()+strlen() combination and less error-prone.
I also suggest to use i++
as a separate statement to avoid any errors in the future (What you have is not wrong; just a general suggestion).
Upvotes: 3
Reputation: 9648
Instead of
words = malloc( strlen( word ) + 1 );
you need to get the proper index in words
and allocate that.
words[i] = malloc( strlen( word ) + 1 );
You haven't attempted to try to compare the tokens. Once you show what you have tried (or after you make an attempt), we will help.
Upvotes: 5