简体   繁体   中英

Why did I get the wrong output and how can I fix this?

I tried to write a program to count the number of occurrences of a given character in a given string.

Here's the program:

#include <stdio.h>
#include <string.h>

int find_c(char s[], char c)
{
    int count;
    int i;
    for(i=0; i < strlen(s); i++)
        if(s[i] == c)
            count++;
   return count;
}

int main()
{
    int number;
    char s[] = "fighjudredifind";
    number = find_c(s, 'd');
    printf("%d\n",number);
    return 0;
}

I was expecting the following output:

3

since the number of occurrences of the character 'd' in the string s is 3.

Each time I tried to run the program, a different number was displayed on the screen. For example, I got the following output while running the program one time:

-378387261

And got this output, when running the program another time:

141456579

Why did I get the wrong output and how can I fix this?

Thanks in advance!

In C Integers are not automatically initialized to zero. The problem is that the count variable is not initialized.
Try initializing the count variable in the find_c function to zero.

Well, Your code is good. Only mistake is, you did not initialize the count to 0. If you do not initialize the variable will hold the garbage value and you will be performing operations on that value. As a result, in the earlier case, you got all the garbage values, when you execute the program each time.

Here is the code:

#include <stdio.h>
#include <string.h>

int find_c(char s[], char c) {
  int count=0;
  int i;
  for(i=0; i < strlen(s); i++)
    if(s[i] == c)
      count++;
      return count;
}

int main() {
  int number;
  char s[] = "fighjudredifind";
  number = find_c(s, 'd');
  printf("%d\n",number);
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM