Z
Z
Zakhar Delov2019-10-20 12:49:52
C++ / C#
Zakhar Delov, 2019-10-20 12:49:52

Why does the search for a word in a string not work?

Good day, I wrote in C ++ an algorithm for finding the first occurrence of a word in a string. The function should return the position number of the first occurrence of the word in the string:

#include <iostream>
using namespace std;
int search(char t[9], char p[3])
{
  int n = strlen(t), m = strlen(p), i = 0, j;
  
  while (i <= (n-m))  //<----------------------тут краш
  {
    j = 0;
    while ((t[i+j] = p[j]) && (j < m))
      j++;
    if (j = m)
      return i;
    i++;
  }
}

int main()
{
  cout << search("badbarrar", "bar");
  
  return 0;
}

The program starts executing and immediately crashes. If you replace (nm) with (mn) - then the program will be executed with the answer -6, which is naturally not correct, but at least it does not crash. What's the problem, thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ronald McDonald, 2019-10-20
@Zoominger

int search(char t[9], char p[3])
Try like this:
int search(char t[], char p[])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question