I am trying to write a C program to calculate the frequency of certain letters within a phrase. The program reads the phrase character by character (via an mmap
that stores characters in an array) and compares the current letter to the desired letter. If there is a match, a counter increments. However, when running my code, I get strange results. The frequency is not incrementing because the letters do not match in the call to strcmp
, even though they do match in the debug. What is happening within my program to cause this behaviour?
char* data; /* input contents from mmap */
char* currChar; /* character being compared to */
char inChar; /* character being read */
...
do {
/* get character */
inChar = 0;
inChar = data[i];
/* debug */
printf("data[i] = %c, inChar = %c, &inChar = %c, currChar = %s\n",
data[i], inChar, &inChar, currChar);
/* if match */
if (strcmp(&inChar, currChar) == 0) {
/* increment frequency */
freq++;
}
/* increment position */
i++;
} while (inChar != 0);
Below is sample output when trying to count the frequency of 'a' in the word "and".
data[j] = a, inChar = a, &inChar = S, currChar = a
data[j] = n, inChar = n, &inChar = S, currChar = a
data[j] = d, inChar = d, &inChar = S, currChar = a
0 instances of a
strcmp
compares strings. &inChar
is not a string.
As you've described your task, you can do the comparison with
if (inChar == *currChar)