below is a small C application. It will ask you for a word to input. It stops asking when has attained four unique words. But in the form shown below it won’t run properly until you uncomment the relevant lines.
#include <stdio.h>
#include <string.h>
#define WORDS_COUNT 4
int main()
{
char* words[WORDS_COUNT];
int words_added = 0;
while (words_added<WORDS_COUNT)
{
puts ("\n-------enter a word-------");
char response[250];
scanf("%s", response);
int i;
int duplicate_flag = 0;
for (i=0; i < words_added; i++)
{
if (strcmp(words[i], response) == 0)
{
duplicate_flag = 1;
break;
};
};
if (duplicate_flag == 0)
{
//char tmp[250];
//strcpy(tmp, response);
words[words_added] = response; //words[words_added] = tmp;
puts("that's new!");
words_added ++;
} else {
puts("you've said that already...");
};
};
return 0;
};
The major difference as you can see is between words[words_added] = response and words[words_added] = tmp.
Why would the tmp variable work and not the response?
I’m guessing that response will have the exact same address every iteration, and tmp will get a new address every iteration. but why? yet they were both declared in same the while loop???
When you assign
words[words_added] = responseyou’re copying the address (not the contents) ofresponseinto the array. So in the original form, your code should see the second word and every subsequent word as duplicates. When you usetmpthe code compares each newresponseto the previoustmpthat was stored in (every location of)words[], then copies it intotmpif it’s not a duplicate.So I suspect that your code will detect a duplicate that immediately follows the original, but not one that occurs 2 or more words later.
The
wordsarray contains 4 pointers, but no memory has been allocated to those pointers.You need to allocate memory for each element of the
wordsarray, and then copy each string into it:Then be sure to
freethe memory at the end of your program: