请注意,在许多其他编译警告中,您应该收到有关声明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()
成功;我得偷懒。