1

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." Then search the document to see if either "ab" or "cd" is there. 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.

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; 

}
JaxJags
  • 41
  • 1
  • 5
  • 1
    Please include the exact details of the crash. Which line of code, the message, if you've used gdb to try to debug it, etc. – Matt Ball Sep 18 '13 at 22:00
  • I get a warning on line 69(the strncmp line) saying "passing argument 1 of'strncmp' makes pointer from integer without a cast." – JaxJags Sep 18 '13 at 22:06
  • 2
    You probably want `ts + i` and `ps + j` instead of `ts[i]` and `ps[j]`, since you want a pointer that's offset into the string and not the value of the character found there. – Dmitri Sep 18 '13 at 22:16
  • 1
    The warning is being generated because you are de-referencing the character by using []. `strncmp()` expects pointers to chars rather than char values directly. Try substituting `ts[i]` for `ts + i` and `ps[j]` for `ps + j`. I have not analyzed your logic, but at least this will probably remove the warning and avoid the crash. –  Sep 18 '13 at 22:17
  • 1
    Fixed! Thanks guys. Just started C, so still learning about everything. – JaxJags Sep 18 '13 at 22:20

2 Answers2

0

strcmp will comapre the strings

use strstr(buffer, s1) != null

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

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
0

use : if(strncmp(&ts[i], ps, k)) or 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. strncmp needs an address [ with proper memory ofcourse ]

resultsway
  • 12,299
  • 7
  • 36
  • 43