【发布时间】:2017-02-25 16:34:58
【问题描述】:
我试图编写一个程序来计算给定字符串中给定字符的出现次数。
这是程序:
#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;
}
我期待以下输出:
3
因为字符串 s 中字符 'd' 的出现次数是 3。
每次我尝试运行程序时,屏幕上都会显示一个不同的数字。例如,我在运行程序一次时得到以下输出:
-378387261
再次运行程序时得到了这个输出:
141456579
为什么我得到了错误的输出,我该如何解决这个问题?
提前致谢!
【问题讨论】:
-
循环开始前的计数值是多少?
-
@stark 我猜它是 0,因为 int 在 C 中默认初始化为零
-
非静态局部(又名自动)变量未初始化,其值为indeterminate。在没有初始化的情况下使用它们会导致未定义的行为。
-
自动变量包含堆栈上最后的任何垃圾
-
@某程序员老兄 谢谢!我将 count 初始化为 0 并解决了问题。
标签: c string output character reverse