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???