I'm still trying to get my head completely around pointers, and so I've been writing a few programs to see what does and doesn't work. This code is to find anagrams. It takes in a one word argument, and checks it against a list of words (words.txt, a sample of which I have attched. The real file is too big to attach here).
If you run the following code
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int isAnagram(char word1[], char word2[]);
void removeFirst(char letter, char* string[]);
void stripWord(char* junk[]);
static const int yes = -1;
static const int no = 0;
int main(int argc, char* argv[]) {
if ( argc != 2 ) {
printf("Please enter exactly one argument\n");
return -1;
} else if ( strlen(argv[1]) > 20 ) {
printf("Please enter an argument that is at most 20 characters\n");
return -1;
}
char word[20];
strcpy(word, argv[1]);
static const char filename[] = "words.txt";
FILE *file = fopen ( filename, "r" );
char line [ 128 ];
char tmp[128];
while ( fgets ( line, sizeof line, file ) != NULL ) {
int i;
for ( i = 0; i < 256; i++ )
{
if ( line[i] == '\n' )
{
line[i] = '\0';
break;
}
}
//sprintf(tmp,"%s",word);
printf("%s\n",word);
if ( isAnagram(line,word) == yes ) printf("%s\n", line);
printf("%s\n",word);
}
fclose ( file );
return 0;
}
int isAnagram(char word1[], char word2[]) {
if ( strlen(word1) != strlen(word2) ) return no;
if ( strcmp(word1,word2) == 0 ) return no;
int i;
for (i=0; i<strlen(word1);i++) {
if ( strchr(word2,word1[i]) == NULL ) return no;
else {
removeFirst(word1[i],&word2);
}
}
return yes;
}
void removeFirst(char letter, char* string[]) {
//remove the first occurrence of 'letter' in 'word'
char temp[20]="";
int i,index;
index = strchr(*string,letter)-*string;
for (i=0; i<strlen(*string);i++) {
if ( i != index ) sprintf(temp,"%s%c",temp,(*string)[i]);
}
strcpy(*string,temp);
}
The problem I'm having is at these lines
Code:
//sprintf(tmp,"%s",word);
printf("%s\n",word);
if ( isAnagram(line,word) == yes ) printf("%s\n", line);
printf("%s\n",word);
When it runs like that, the output will show you the value of the variable 'word', before and after the execution of the isAnagram function. This value appears to change as the program runs.
However, if you uncomment the sprintf line, and pass the value tmp instead of word, like so
Code:
sprintf(tmp,"%s",word);
printf("%s\n",word);
if ( isAnagram(line,tmp) == yes ) printf("%s\n", line);
printf("%s\n",word);
the value of word doesn't change at all, and it works fine.
So, my question is, Why is 'word' being changed by isAnagram when I didn't pass it's address to the function?
Thank you