C语言指针函数

来源:百度知道 编辑:UC知道 时间:2024/05/26 09:00:03
用指针编写函数,在一个字符串中统计给定字符的个数,利用该函数编程,输入字符串,统计其中有几个a几个b几个c 我下面的代码运行主调函数时无法计算给定的字符的个数,请大家帮我看看到底错在哪了。 谢谢。
#include "stdio.h"
char show (char *c,char a)
{
char *p ;
int num;
p=c;
for (p=c;*p!='\0';p++)
if (*p==a)
num++;
return num;
}
main ( )
{
int q,w,e ;
char s[60];
q=show(s,'a');
w=show(s,'b');
e=show(s,'c');
printf ("a有%d个,b有%d个,c有%d个。",q,w,e);
}

#include "stdio.h"
int show (char *c,char a) //这里返回值改成int
{
char *p ;
int num = 0; //这里初始化为0
p=c;
for (p=c;*p!='\0';p++)
if (*p==a)
num++;
return num;
}
main ( )
{
int q,w,e ;
char s[60] = "abcedfagcebbbb"; //这里要给字符数组赋值
q=show(s,'a');
w=show(s,'b');
e=show(s,'c');
printf ("a有%d个,b有%d个,c有%d个。\n",q,w,e);
}

num没有赋初值,所以会出错.

应改为
int num=0;

还有没见到绐s[]数组输入初值,或初始化.
scanf("%s",s);