简体   繁体   English

崩溃的C程序

[英]Crashing C Program

I am trying to write an algorithm that searches a document for a particular chunk. 我正在尝试编写一种算法来搜索文档中的特定块。 If the chunk is found, a 1 will be returned, if not, a 0. Basically if the chunk is "abcd" and a particular length is 2, the chunk would be split into "ab" and "cd." 如果找到了块,则将返回1,否则将返回0。基本上,如果块为“ abcd”且特定长度为2,则该块将分为“ ab”和“ cd”。 Then search the document to see if either "ab" or "cd" is there. 然后搜索文档以查看是否存在“ ab”或“ cd”。 I think my algorithm is pretty much fine, but the program keeps crashing. 我认为我的算法还不错,但是程序一直崩溃。 I think it has to do with the strncmp, but I can't figure out how to fix it. 我认为这与strncmp有关,但我不知道如何解决它。

Here's my code: 这是我的代码:

int main( )
{
         char s1[] = "abcdef";
         char s3[] = "cd";
         size_t s1Size = strlen(s1);
         int k = 2;

         if(simple_substr_match(s3,k,s1,s1Size))
            printf("Match Found\n");
         else
            printf("No Match Found\n");
         return 0;  
}

int simple_substr_match(const unsigned char *ps, int k, const unsigned char *ts, int n)
{
        int isMatch; 
        int i;
        int j; 

        for(i=0;i<n;i++)
        {
           if(strncmp(ts[i], ps, k))
           {
              isMatch = 1; 
           }
        }

        return isMatch; 

}

strcmp will comapre the strings strcmp将比较字符串

use strstr(buffer, s1) != null 使用strstr(buffer, s1) != null

http://en.cppreference.com/w/c/string/byte/strstr http://en.cppreference.com/w/c/string/byte/strstr

use : if(strncmp(&ts[i], ps, k)) or if(strncmp(ts+i, ps, k)) 使用:if(strncmp(&ts [i],ps,k))或if(strncmp(ts + i,ps,k))

pay attention to warnings. 注意警告。 By using ts[i] you are derefing and comparing with value which is a char. 通过使用ts [i],您将取消引用并与作为char的value进行比较。 strncmp needs an address [ with proper memory ofcourse ] strncmp需要一个地址[具有适当的课程记忆]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM