C 数组搜索中的分段错误
我有一个程序,它接收一个字符数组,数组中有许多以标记为界的消息。这些“标记”是字符数组中随机定位的字符序列 下面是一个示例:给定一个字符数组:C 数组搜索中的分段错误,c,arrays,loops,char,segmentation-fault,C,Arrays,Loops,Char,Segmentation Fault,我有一个程序,它接收一个字符数组,数组中有许多以标记为界的消息。这些“标记”是字符数组中随机定位的字符序列 下面是一个示例:给定一个字符数组:{'a'、's'、't'、'1'、'm'、's'、'g'、'e'、'x'、'1'、's'、't'、'1'、's'、's'、's'、's'、's'、'g'、'e'、'x'、'1'、'z'}。标记“st1”表示包含每个字符的消息的开头,直到找到一个“ex1”序列,这是消息结尾的标记,它会在数组中不断搜索下一个表示新消息开头的“st1”序列。在此示例中,消息为:
{'a'、's'、't'、'1'、'm'、's'、'g'、'e'、'x'、'1'、's'、't'、'1'、's'、's'、's'、's'、's'、'g'、'e'、'x'、'1'、'z'}代码>。标记“st1”
表示包含每个字符的消息的开头,直到找到一个“ex1”
序列,这是消息结尾的标记,它会在数组中不断搜索下一个表示新消息开头的“st1”序列。在此示例中,消息为:“msg”
、
和“st1ssg”
这是我的程序-我不断遇到分段错误:
int main(int argc, char const *argv[])
{
char array[] = {'a','s','t','1','m','s','g','e','x','1','r','s','t','1','s','t','1','s','s','g','e','x','1','z'};
int state = 0;
int found = 0;
int i,j;
int msgStartIndex;
int msgEndIndex;
while(array[i]){
if((array[i] == 's' && state == 0) || (array[i] == 't' && state == 1) || (array[i] == '1' && state == 2) ){
state++;
if(!found && state == 3){
msgStartIndex = i+1;
found = 1;
}
}
else if(!found && (array[i] = 't' && state == 2))
state = 2;
else if(!found)
state = 0;
if((array[i] == 'e' && state == 3) || (array[i] == 'x' && state == 2) || (array[i] == '1' && state == 1) ){
state--;
if(found && state == 0){
found = 0;
msgEndIndex = i-3;
for(j=msgStartIndex; j < msgEndIndex+1; j++)
printf("%c",array[j]);
printf("\n");
}
}
else if(found && (array[i] == 'e' ) && (state == 2 || state == 1))
state = 2;
else if(found)
state = 3;
i++;
}
return 0;
}
int main(int argc,char const*argv[])
{
字符数组[]={'a','s','t','1','m','s','g','e','x','1','r','s','t','1','s','t','1','s','s','s','s','g','e','x','1','z'};
int state=0;
int=0;
int i,j;
int msgStartIndex;
int msgEndIndex;
while(数组[i]){
if((数组[i]='s'和&state==0)| |(数组[i]='t'和&state==1)| |(数组[i]='1'和&state==2)){
状态++;
如果(!found&&state==3){
msgStartIndex=i+1;
发现=1;
}
}
else如果(!found&&(数组[i]='t'&&state==2))
状态=2;
如果(!找到),则为else
状态=0;
if((数组[i]='e'和&state==3)| |(数组[i]='x'和&state==2)| |(数组[i]='1'和&state==1)){
国家--;
如果(发现和状态==0){
发现=0;
msgendex=i-3;
对于(j=msgStartIndex;j
您从未费心初始化循环计数器:
int i,j;
while(array[i]){
因此,您只需开始使用i
中的任意随机垃圾即可。如果垃圾恰好大于数组的长度,程序将停止运行。您从未费心初始化循环计数器:
int i,j;
while(array[i]){
因此,您只需开始使用i
中的任意随机垃圾即可。如果垃圾恰好大于数组的长度,程序将停止运行。变量I未初始化,而且数组也未以零结尾
int i,j;
/...
while(array[i]){
因此循环具有未定义的行为
您可以在数组中保留一个字符串,并使用header
中声明的标准函数strstr
查找开始和结束标记。变量I未初始化,而且数组未以零结尾
int i,j;
/...
while(array[i]){
因此循环具有未定义的行为
您可以在数组中保留一个字符串,并使用header中声明的标准函数strstr
查找起始标记和结束标记。如果(!found&&(array[i]='t'&&state==2))
此条件违反如果(!found&(array[i]='t'&state==2))
此条件违反了oh true,我将i初始化为0,它可以工作,但程序失败,因为数组不是以null结尾的?如果(!found&&(array[i]),您还有else='t'
-如果测试中的赋值通常是一个bug的迹象…也许它应该是=
。哦,是的,我将i初始化为0,它可以工作,但程序失败,因为数组不是以null结尾的?如果(!found&&(array[i]),你还有否则='t'
-如果测试中的赋值通常是bug的迹象,那么它可能应该是=
。