因此,在本练习中,我需要制作一个程序,输出输入中不同字符频率的直方图。这是我迄今为止的代码:
#include <stdio.h>
int main(){
int c,i;
int m = 1;
int a[m];
i = 0;
while ((c = getchar()) != EOF){
m++;
a[i] = c;
++i;
/* assign a a string of chars*/
}
i = 0;
int r;
int s;
while (i<m){
s = 0;
for(r = 0; r < m; r++){
if (a[r] == a[i] && a[i] != 0 && a[i] != 'n' && a[i] != EOF) {
s++;
/*checks for every character in the strig if there is another one that's the same and adds one to the s var*/
}
}
++i;
putchar(a[i]);
putchar('|');
printf("%d", s);
putchar('n');
/*ouptputs the charaters and his frequency in the input*/
}
}
如果我们运行这个并输入,比如abbcd,它将输出:
a|0
b|1
b|2
c|2
d|1
(这仍在进行中,因此并不完美)
我的问题是,如果我写的字符超过7个,它将运行一段时间而没有任何输出,然后退出,退出代码为-103741819(0xC0000005)。
问题出在我的处理器上吗?我有一辆i7-3540M。我的意思是,我知道这很糟糕,但这么糟糕?
不,您的处理器没有问题。这里的问题是一种未定义的行为。
特别是while循环中的这段代码:
a[i] = c;
这只对i = 0
有好处。然而,一旦i > 0
,这将开始生成未定义的行为,因为数组a
被声明为只适合一个元素,比如int m = 1; int a[m];
。
换句话说,您正试图在数组中存储超出其定义边界的内容。
此外,正如一些人在评论部分指出的那样,不能只增加m
并期望数组a
的大小为"0";生长";。如果你想让你的数组";生长";在程序运行(并在其中存储更多项目)时,您必须学习如何动态管理内存。