【问题标题】:segmentation fault in array search C数组搜索中的分段错误 C
【发布时间】:2016-10-03 18:20:45
【问题描述】:

我有这个程序,它接收一个 char 数组,其中包含许多由标签限制的消息。这些“标签”是随机位于字符数组中的字符序列。

这里是一个例子:给定一个字符数组:{'a','s','t','1','m','s','g','e','x','1','r','s','t','1','s','t','1','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;
}

【问题讨论】:

标签: c arrays loops char segmentation-fault


【解决方案1】:

变量 I 没有被初始化,而且数组不是以零结尾的。

int i,j;
/...
while(array[i]){

所以循环具有未定义的行为。

您可以在数组中保留一个字符串并使用标头&lt;string.h&gt; 中声明的标准函数strstr 来查找开始和结束标记。

【讨论】:

    【解决方案2】:

    您从不费心初始化循环计数器:

    int i,j;
    
    while(array[i]){
    

    所以您只需开始使用i 中的任何随机垃圾即可。如果这些垃圾恰好比数组的长度大,那么你的程序就会繁荣起来。

    【讨论】:

    • 哦,是的,我将 i 初始化为 0,它可以工作但程序失败,因为数组不是以 null 结尾的?
    • 你也有else if(!found &amp;&amp; (array[i] = 't' - 在if 测试中分配通常是一个错误的迹象......也许它应该是==
    猜你喜欢
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 2013-01-29
    • 1970-01-01
    相关资源
    最近更新 更多