首页 > 解决方案 > 在 C 上执行程序时没有给出输出

问题描述

当我用 gcc 编译这个程序时:

#include <stdio.h>

/* This program accepts some text as an input and gives the output
 * of longest word and shortest word lengths*/

int main(){
int c, i, wordcount, symbolcount, longestword, shortestword;
wordcount = symbolcount = longestword = shortestword = 0;
int wlength[1];
while((c = getchar()) != EOF){
    ++symbolcount;
    if(c == ' ' || c == '\n' || c == '\t'){
        ++wordcount;
        wlength[wordcount];
        wlength[wordcount - 1] = symbolcount;
        symbolcount = 0;
    }
}
for(i = 0;i <= wordcount;)
wlength[0] = longestword;
wlength[i] = shortestword;
while(shortestword < 1){
    if(shortestword == longestword){
        continue;
        ++i;
    }else if(shortestword < longestword && shortestword > 0){
        shortestword = wlength[i];
        break;
    }
}
for(i = 0; i <= wordcount - 1; ++i){
    if(wlength[i] > longestword){
        longestword = wlength[i];
    }else if(wlength[i] < longestword && wlength[i] > shortestword){
        continue;
    }else{
        wlength[i] = shortestword;
        }
    }
printf("%d\t%d", longestword, shortestword);
return 0;
}

没有错误或警告。但是当我尝试运行它时,它接受输入,但根本没有输出。即使我按 Ctrl + D(我在基于 debian 的发行版上工作),当前的终端会话也不会暂停,程序只会继续运行。可能是什么问题?

标签: coutput

解决方案


问题是

int wlength[1];

只声明一个包含一个元素的数组,但您使用越界访问

shortestword = wlength[i];

这是C 语言中未定义的行为,任何事情都可能发生,包括您所观察到的。

要解决此问题,请使用您期望的尽可能多的元素声明数组i。确保您的循环i仅采用不超过数组元素计数的值。


推荐阅读