#include #include #include #include char *randstr ( int l ) { char *S; int i; S = (char *)malloc((l+1) * sizeof(char)); S[l] = '\0'; for (i=0; i= 2*m - 1) && (G[i])) ++cnt; /* Match found */ } /* Copy the match locations in the array match[]. At this moment, cnt stores the exact number of matches. So a precise size allocation for match[] is posssible. */ match = (int *)malloc((cnt+1)*sizeof(int)); match[0] = cnt; /* Store the number of matches in match[0]. match[1], match[2], ..., match[cnt] will store the matching indices. */ j = 1; /* j is now used as the writing location in match[] */ for (i=2*m-1; i match2[match2[0]]) break; /* No further match possible */ /* Find the first location of a match */ while ((j <= match2[0]) && (k > match2[j])) ++j; /* Each following match of T2 in S produces a pattern match */ for (k=j; k<=match2[0]; ++k) printf(" (%d,%d)", match1[i], match2[k]); } printf("\n"); /* Clean up locally allocated memory */ free(S); free(T1); free(T2); free(match1); free(match2); } int main ( int argc, char *argv[] ) { int n, m; srand((unsigned int)time(NULL)); if (argc >= 3) { n = atoi(argv[1]); m = atoi(argv[2]); } else { printf("n = |S| = "); scanf("%d", &n); printf("m = |T| = "); scanf("%d", &m); } printf("\n*** String matching\n"); strmatch(n,m); printf("\n*** Pattern matching\n"); patmatch(n,m); exit(0); }