读书人

内存储器溢出OR编译器不给力

发布时间: 2012-10-21 09:00:07 作者: rapoo

内存溢出OR编译器不给力?
一个统计各个数字,空白符及其他字符出现的次数 的小程序[code=C/C++][/code]

#include<stdio.h>
#include<stdlib.h>
/* 统计各个数字,空白符及其他字符出现的次数 */
int main()
{
int c, i, nwhite, nother;
int ndigit[10];
for(i=0;i<10;i++)
ndigit[i]=0;
while((c = getchar()) != EOF)
if ( c>= '0' || c <= '9')
++ndigit[c-'0'];
else if( c == ' ' || c == '\t' || c == '\n')
++nwhite;
else
++nother;


printf("digit =");
for(i=0;i < 10; ++i)
printf("%d",ndigit[c-'0']);
printf("\n");
printf("white space = %d,other space = %d\n",nwhite,nother);
system("pause");
}
但是输入测试数据的时候,控制台都会显示出错而显示要关闭。

[解决办法]
数组溢出。
[解决办法]
++ndigit[c-'0']; c = 67 ,0 = 48 ,直接越界。

还有printf("digit ="); 打印的数,后面也没有写出,不过这个不会报错。
[解决办法]
错误的地方不少,都帮你改过来了:

C/C++ code
/* 统计各个数字,空白符及其他字符出现的次数 */#include <stdio.h>#include <stdlib.h>int main(int argc, char* argv[]){    int c, i, nwhite = 0, nother = 0;    int ndigit[10];    for(i = 0; i < 10; i++)        ndigit[i]=0;    while((c = getchar()) != 27)    /* ESC键退出 */        if (c >= '0' && c <= '9')            ++ndigit[c - '0'];        else if(c == ' ' || c == '\t' || c == '\n')            ++nwhite;        else            ++nother;         printf("digit =");    for(i = 0; i < 10; ++i)        printf("%d ", ndigit[i]);    printf("\n");    printf("white space = %d, other space = %d\n", nwhite, nother);      system("pause");     return 0;}
[解决办法]
main函数里面的参数是用来接受传递的命令的。程序编译完成之后,运行时如果在程序里面用到的话就要传递参数。是个可变参数,第一个是数目,第二个就是命令。自己仔细看下基础吧。推荐《C与指针》
探讨

引用:
没什么不妥,习惯问题,因为你的EOF需要按组合键CTRL+Z/CTRL+C/CTRL+D,不同的操作系统有不同的解析。


引用:

引用:
错误的地方不少,都帮你改过来了:

C/C++ code

/* 统计各个数字,空白符及其他字符出现的次数 */
#include <stdio.h>
#include ……

读书人网 >C语言

热点推荐