【发布时间】:2016-02-17 13:58:01
【问题描述】:
我想做什么
我正在尝试计算字符串中的字符数。我尝试将字符串保存在数组CH[100] 中,然后启动switch-statement 以查找字符Q 重复了多少...
守则
114.c
#include <stdio.h>
#define SIZE 100
int main(int argc, char* argv[])
{
char* CH[SIZE];
int alpha[26] = { 0 };
unsigned int i = 0;
printf("name\n");
scanf("%s", CH);
while(i < SIZE){
if(CH[i] != '\0')
{
switch(CH[i])
{
case 'a':
case 'A': ++alpha[0]; break;
case 'b':
case 'B': ++alpha[1]; break;
case 'c':
case 'C': ++alpha[1]; break;
. . .
. . .
. . .
case 'y':
case 'Y': ++alpha[24]; break;
case 'z':
case 'Z': ++alpha[25]; break;
}//end switch
}else{ break;}
++i;
}//end while
for(int j = 65; j < 91; ++j)
{
if(alpha[j- 65] != 0)
printf("%s\t - %d times\n",(char) j,alpha[j- 65]);
}
}
编译和执行:
[ar.lnx@host Documents] $ gcc 114.c -o x
[ar.lnx@host Documents] $ ./x
donner le nom
anas
Segmentation fault (core dumped)
[ar.lnx@host Documents] $
我不明白是什么问题,谁能帮我看看这里发生了什么
【问题讨论】:
-
检查索引!并使用更好的测试字符串,例如
abc...z。顺便说一句:那太容易出错了;使用代码直接索引到数组中。并且不要对变量使用全大写。 -
你使用
%s来打印一个字符;请改用%c。 (%s需要char *,它会取消引用。作为可变参数传递的 ASCII 值不是有效地址,可能没有正确的大小。编译时启用警告以了解格式/参数不匹配。) -
注意,您可以通过设置
len=strlen(CH);并将 while 设为 for 循环for(i=0; i<len; i++)来摆脱 while 内的 if
标签: c arrays string switch-statement scanf