题4、
The following C++ code tries to count occurence of each ASCII charcaterin given string and finally print out the occurency numbers.(下面C++代码用来统计每个ASCII字符的出现次数,最后给出出现数值。)
#include <iostream>
#include <cstdlib>
void histogram(char *src)
{
int i;
char hist[256];
for(i = 0; i < 256; i++)
{
hist[i] = 0;
}
while(*src != '\0')
{
hist[*src]++;
}
for(i = 0; i <= 256; i++)
{
printf("%d ", hist[i]);
}
}
int main()
{
char *src = "aaaabcdefghijklmnopqrst1234567890";
histogram(src);
return 0;
}
If there may be some issue in the code above, which line(s) would be?(如果上面代码有错,将在哪行出错,如何修改?)
答案:这段代码有两个错误:
(1)hist[*src]++; 这行应该修改为hist[*src++]++;这是因为在while(*src != '\0')循环体是看*src的值是否为'\0'来作为结束的。所以src必须递加。否则hist[*src]其实就是hist['a'],'a'会隐式转换成97也就是hist[97]++不停递加,进入死循环。
(2)for(i = 0; i <= 256; i++)这一行应该修改为for(i = 0; i <= 256; i++),否则会超界。


被折叠的 条评论
为什么被折叠?



