【问题标题】:Why the last element of the array is setting to '-1' automatically?为什么数组的最后一个元素自动设置为“-1”?
【发布时间】:2013-11-20 12:53:14
【问题描述】:
#include <stdio.h>
#define IN 1
#define OUT 0
#define maxword 15

main()
{
int j,i,state,c,nc_word;
nc_word = 0;
int count [maxword];
for(i=0;i<=maxword;i++)
    count[i]=0;
state = OUT;

while((c=getchar())!= EOF)
{
    if( c == ' '|| c == '\t'||c == '\n')
    {
       if (state == IN){
        ++count[nc_word];
        nc_word = 0;
       }
       state = OUT;

    }
    else
    {
        state = IN;
        ++nc_word;
    }
 }
for(i=13 ; i>=1 ; --i)
 {
    printf("\n%d",i);
   for(j=1;j<=count[i];j++){
        printf(" *");
   }
 }
 }

此程序打印单词中字符数的直方图。但它将数组 count[] 的最后一个元素设置为 -1(在我的例子中,-1 是 EOF 值)。 例如,如果输入中有一个 14 字符的单词,count[14] 应该为 1,但它不起作用.. 它总是设置为 -1。为什么会这样?

【问题讨论】:

  • count 中的有效索引为0 to maxword-1

标签: c arrays histogram


【解决方案1】:

它应该是&lt;,而不是for(i=0;i&lt;=maxword;i++) 中的&lt;=。 您正在尝试访问不属于您的数组的内存空间。

【讨论】:

  • 哇,砰!...它奏效了。我不小心写了
【解决方案2】:

检查一次您的索引,它正在打印垃圾值。 先生,您的这句话在什么空间存在?我不明白

++count[nc_word];

【讨论】:

  • 它不是简洁地打印垃圾......它正在打印 -1 这是 EOF 值......哪个数组用于检测元素的结尾......无论如何......thanx ..我仍然没有'不知道你想对“++count[nc_word];”说什么声明。
猜你喜欢
  • 2022-07-06
  • 2021-09-20
  • 2019-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
  • 2021-10-28
相关资源
最近更新 更多