Segmentation fault (core dumped) 执行代码时出错
Segmentation fault (core dumped) Error when executing code
需要帮助找出执行代码时出现分段错误(核心已转储)的原因。我试图研究原因,但没有发现与我的 code.Sorry 相关的任何内容,因为错误代码对编程来说仍然是新手
#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。str[q] != 1000
也总是为真,因为 str[q]
是 char
类型它不能保存值 1000
。
因此你的程序进入了无限循环。因此,它最终访问了超出 str
范围的内存。并且这里的行为没有定义。大多数情况下,您的程序会崩溃。
您的意思可能是 -
while ( q != 1000)
这会起作用并且不会导致任何未定义的行为,但请注意字符串在数组的总长度之前结束。该字符串在遇到 '[=19=]'
字符时结束。您应该使用条件 -
while ( q < 1000 && str[q] != '[=12=]')
此外,请确保不要调换条件的顺序,否则您将再次读取越界内存。
需要帮助找出执行代码时出现分段错误(核心已转储)的原因。我试图研究原因,但没有发现与我的 code.Sorry 相关的任何内容,因为错误代码对编程来说仍然是新手
#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。str[q] != 1000
也总是为真,因为 str[q]
是 char
类型它不能保存值 1000
。
因此你的程序进入了无限循环。因此,它最终访问了超出 str
范围的内存。并且这里的行为没有定义。大多数情况下,您的程序会崩溃。
您的意思可能是 -
while ( q != 1000)
这会起作用并且不会导致任何未定义的行为,但请注意字符串在数组的总长度之前结束。该字符串在遇到 '[=19=]'
字符时结束。您应该使用条件 -
while ( q < 1000 && str[q] != '[=12=]')
此外,请确保不要调换条件的顺序,否则您将再次读取越界内存。