c - Segmentation fault (core dumped) 执行代码时出错
问题描述
执行代码时需要帮助找出分段错误(核心转储)的原因。我试图研究原因,但没有发现与我的代码有关的任何东西。对不起,对于编程来说仍然是新的糟糕代码
#include <stdio.h>
int main(void)
{
char str[1000];
int counta , counte, counti,counto,countu;
int q =0;
printf("Enter a String: \n");
scanf("%s" , str);
//if (feof(stdin)) break; //CRTL D TO STOP
while(1==1 && str[q] != 1000 ) {
if(str[q] == 'a')
{
q++;
counta++;
}
else q++;
}
q = 0;
//while(str[q]
printf("%d" , counta);
return 0;
}
解决方案
您的程序有一个带有条件的 while 循环 -
while (1==1 && str[q] != 1000)
1==1
是没用的,因为 1 总是等于 1。 thestr[q] != 1000
也将永远为真,因为str[q]
它的类型char
不能保存值1000
。
因此,您的程序进入无限循环。因此,它最终访问了超出str
. 并且这里的行为没有定义。大多数情况下,您的程序会崩溃。
你可能的意思是条件是 -
while ( q != 1000)
这将起作用并且不会导致任何未定义的行为,但请注意字符串在数组总长度之前结束。字符串在遇到'\0'
字符时结束。你应该使用条件 -
while ( q < 1000 && str[q] != '\0')
另外,请确保不要切换条件的顺序,否则您将再次读取超出范围的内存。
推荐阅读
- javascript - Typescript - 获取满足条件的数组
- python - Python 3.7.1 ANT+ TKinter - 在 Tkinter 中显示来自 ANT+ 设备的实时数据
- sql - 获取过去 6 个月的条目总和(不完整的月份)
- javascript - 如何通过 vue-cli 3 配置 webpack 以使用 sass
- php - Laravel 队列 - 作业之间暂停
- php - Symfony 致命错误:require():无法打开所需的 'C:\xampp\htdocs\app\cache\prod/doctrine/orm/Proxies\__CG__MediaBundleEntityMedia.php'
- php - symfony 4 - 所有页面仅用于记录
- javascript - Panel toggleDown 仅选中复选框。Javascript/jQuery
- neo4j - 匹配满足两个或多个关系 (AND) 关系的 Neo4j 节点的表达式
- fortran - Fortran 中子程序的有条件使用