将字符串和字符传递给函数

时间:2013-05-19 02:58:58

标签: c

我写的这段代码应该读一个句子和一个字符来检查那个句子中该字符的出现。它在我在main中编写代码时有效,但是当我尝试使用函数时它不起作用。我遇到的问题是向函数参数声明一个字符串和一个变量char。有什么问题?

#include<stdio.h>
#include<string.h>
int occ(char*,char);
int main ()
{
    char c,s[50];
    printf("enter a sentece:\n");gets(s);
    printf("enter a letter: ");scanf("%c",&c);
    printf("'%c' is repeated %d times in your sentence.\n",c,occ(s,c));
}
int occ(s,c)
{
    int i=0,j=0;
    while(s[i]!='\0')
    {
        if(s[i]==c)j++;
        i++;
    }
    return j;
}

1 个答案:

答案 0 :(得分:4)

请注意,您应该收到有关occ声明与其定义之间原型不匹配的警告,以及其他一系列编译警告。

当你写:

int occ(s,c)
{

您正在使用预标准或K&amp; 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()是否成功;我变得懒惰。