I wrote this program that get words from user and if it was entered already it will print you loose
but when I the first code crashs but the second code works! why the first code is crashs?
#include <stdio.h>
#include <string.h>
int getword(char *word);
int find(char * words[], int i);
char *words[100];
int main()
{
int i = 0;
while (i < 100)
{
printf("enter your word");
get_word(words[i]);
if (find(words, i))
{
printf("you lose");
exit(1);
}
i++;
}
printf("no body wins");
}
int get_word(char *word)
{
word= (char *)malloc(sizeof(char)*100);
scanf("%s", word);
}
int find(char * words[],int i)
{
int index = 0;
while (index < i)
{
if (!strcmp(words[index++], words[i]))
return 1;
}
return 0;
}
#include <stdio.h>
#include <string.h>
int getword(char *words[], int i);
int find(char * words[], int i);
char *words[100];
int main()
{
int i = 0;
while (i < 100)
{
printf("enter your word");
get_word(words, i);
//printf("hi%s", words[0]);
if (find(words, i))
{
printf("you lose");
exit(1);
}
i++;
}
printf("no body wins");
}
int get_word(char *words[], int i)
{
words[i] = (char *)malloc(sizeof(char)* 100);
scanf("%s", words[i]);
}
int find(char * words[], int i)
{
int index = 0;
while (index < i)
{
if (!strcmp(words[index++], words[i]))
return 1;
}
return 0;
}
The diff:
get_word(words[i]);
get_word(words, i);
int get_word(char *word)
{
word= (char *)malloc(sizeof(char)*100);
scanf("%s", word);
}
int get_word(char *words[], int i)
{
words[i] = (char *)malloc(sizeof(char)* 100);
scanf("%s", words[i]);
}