c - 在 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 的发行版上工作),当前的终端会话也不会暂停,程序只会继续运行。可能是什么问题?
解决方案
问题是
int wlength[1];
只声明一个包含一个元素的数组,但您使用越界访问
shortestword = wlength[i];
这是C 语言中未定义的行为,任何事情都可能发生,包括您所观察到的。
要解决此问题,请使用您期望的尽可能多的元素声明数组i
。确保您的循环i
仅采用不超过数组元素计数的值。
推荐阅读
- ansible - 如何检索特定字典的名称 - Ansible
- reactjs - 当我只在主页上需要它们时,是否需要将数据放入 redux 存储中?
- php - 如何将 Laravel (v5.6.29) 项目(应用程序)放到平台 WebFaction(网络托管服务器)上
- django - Django 在 Docker 中加载错误的设置模块
- python - Mac OSX 上的 Matplotlib,python 3.6 不一致且极其脆弱
- python-3.x - 递归给了我一个加数的总和。但是我怎么能指望 Python 在我的函数中不使用全局变量的一些递归呢?
- javascript - CouchDB 文档中的总和值
- python - Django:仅在其个人资料上显示链接到特定用户的约会
- asp.net - ASP.NET 表单的非空验证
- python - 脚本仅在我重新启动 shell 时才有效