My first function checks for the number of letters that a substring contains from its string.
int num_matches(char* word, char* letters) {
char scrabble[128];
strcpy(scrabble, letters);
int num = 0;
for (int i = 0; i < strlen(word); i ) {
if (strchr(letters, word[i]) == NULL) {
return -1;
}
for (int j = 0; j < strlen(letters); j ) {
if (word[i] == letters[j]) {
num ;
scrabble[j] = '\0';
break;
}
}
}
return num;
}
It returns 4 for "QWOP", "QWOP". However, inside the following function it is returning the same incorrect value for every function call, even when buff and letters print as "QWOP", "QWOP" from my debugging attempt.
void read_words(int num_count[128], char* (*word_idx)[128], int argc, char** argv) {
FILE* fp = fopen(argv[1], "r");
char* letters = argv[2];
int idx = 0;
char buff[128];
int result = 0;
while (fgets(buff, 128, fp) != NULL) {
printf("buff:%s letters:%s\n", buff, letters);
result = num_matches(buff, letters);
printf("result: %d\n", result);
num_count[idx] = result;
char* word = malloc(strlen(buff) 1);
strcpy(word, buff);
(*word_idx)[idx] = word;
idx ;
result = 0;
}
fclose(fp);
}
buff:QWOP
letters:QWOP
result: -1
My txt file:
ABC
DEFG
QWOP
QWOP
QUOKKA
QUOLL
QUASH
QUANDONG
Since fgets stops at a newline and there are no spaces in my text file, I don't think there should be any problems with reading buff.
CodePudding user response:
fgets reads the data with \n
character at the end.
Your function will fail in this case. It is very easy to test:
int main(void)
{
printf("%d\n", num_matches("ABCD", "ABCD"));
printf("%d\n", num_matches("ABCD\n", "ABCD"));
}
Result:
4
-1
You need to remove \n
from the buff.
Another problem is the second function. The parameter char* (*word_idx)[128]
is a pointer to an array of 128 pointers to char. I do not think that is something you want.