請注意,你應該得到一個關於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 –