سؤال

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)

نصائح أخرى

strcmp expects a '\0'-terminated string. inChar is simply a character, with "some unknown value" following it on the stack.

If you are just going to compare characters, why not if (inChar == *currChar)

strcmp() is to compare zero-terminated strings. You are not comparing strings. you are comparing the value of two individual character values. Here is the Reference which states,

"This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached."

just remove your strcmp function to:

if (inChar == *currChar) ...

Try this:

for(j=0;currChar[j]!='\0;j++)
{
   for(i=0;data[i]!='\0';++i)
   {
       if(currChar[j]==data[i])
           ++freq;
   }
   printf("Frequency of %c = %d", currChar[j], freq);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top