请注意,你应该得到一个关于occ
的声明和它的定义之间的原型不匹配的警告,其中包括编译警告的主机。
当你写:
int occ(s,c)
{
您使用的是预标准或K & [R风格的函数,默认参数类型 - 因为你没有指定任何类型 - 是int
。对于char
参数没有问题; char *
参数不正确。
所以,一切分开,你应该写:
int occ(char *s, char c)
{
与原型一致。
当我编译你的代码,我得到的编译错误:
$ gcc -O3 -g -std=c99 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition -c wn.c
wn.c:4:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes]
wn.c: In function ‘main’:
wn.c:4:5: warning: old-style function definition [-Wold-style-definition]
wn.c: In function ‘occ’:
wn.c:11:5: warning: old-style function definition [-Wold-style-definition]
wn.c:11:5: warning: type of ‘s’ defaults to ‘int’ [enabled by default]
wn.c:11:5: warning: type of ‘c’ defaults to ‘int’ [enabled by default]
wn.c:11:5: error: argument ‘s’ doesn’t match prototype
wn.c:3:5: error: prototype declaration
wn.c:11:5: error: argument ‘c’ doesn’t match prototype
wn.c:3:5: error: prototype declaration
wn.c:14:12: error: subscripted value is neither array nor pointer nor vector
wn.c:16:13: error: subscripted value is neither array nor pointer nor vector
wn.c:11:5: warning: parameter ‘s’ set but not used [-Wunused-but-set-parameter]
注意:它不会花费太多修复代码 - 这编译干净。但是,它确实使用fgets()
而不是gets()
。你应该忘记gets()
现在存在,你的老师应该被解雇提及它的存在。
实施例运行:
$ ./wn
enter a sentence: amanaplanacanalpanama
enter a letter: a
'a' is repeated 10 times in your sentence.
$
代码:
#include <stdio.h>
int occ(char*, char);
int main(void)
{
char c, s[50];
printf("enter a sentence: ");
fgets(s, sizeof(s), stdin);
printf("enter a letter: ");
scanf("%c", &c);
printf("'%c' is repeated %d times in your sentence.\n", c, occ(s, c));
return 0;
}
int occ(char *s, char c)
{
int i=0, j=0;
while (s[i]!='\0')
{
if (s[i]==c)
j++;
i++;
}
return j;
}
的代码应该检查两个fgets()
和scanf()
成功;我得到了懒惰。
除了你从别人那里得到的答案以外,避免使用gets(s);尽可能多地查看此手册页的bug部分以获取更多信息http://linux.die.net/man/3/gets –