Your return -1; is within the loop. It'll return if the first if (B[i+c]== C) comparison you do fails. Move it out of the loop.
You compare the wrong things. B[i+c] is a char and C is a char*. If you want to compare strings, use strcmp, strncmp or memcmp depending on the situation and supply the correct arguments.
strcmp for arbitrary strings that you want to compare until the null terminator is found in both.
strncmp if you want to limit the comparison to n number of characters but still be stopping at a null terminator. Seems like a good fit for a substring comparison.
memcmp if you are sure that the length you supply will not make it pass a null terminator since it doesn't check for a null terminator. It just compare bytes in memory where you tell it to, for as long as you tell it to.
I'm using memcmp in this example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SS_NOTFOUND ((size_t)-1)
size_t strsearch(const char *B, const char *C) {
size_t Blen = strlen(B);
size_t Clen = strlen(C);
// If Blen < Clen, there's no way C can
// can be a substring of B:
if(Blen < Clen) return SS_NOTFOUND;
// Subtract the length of C from the length of B. There is no need to
// search in B beyond the point where C can't fit:
Blen -= Clen;
for (size_t i = 0; i <= Blen; i++) {
// memcmp is fine here since no null terminators will be passed
// due to the check (Blen < Clen) at the start and the subtraction
// of Clen from Blen above.
if (memcmp(B + i, C, Clen) == 0) return i;
// char* char*
}
return SS_NOTFOUND;
}
int main() {
char B[] = "thisatest";
char C[] = "tes";
size_t pos = strsearch(B, C);
if(pos == SS_NOTFOUND) puts("sorry, not found");
else printf("Found at index %zu\n", pos);
}
Output:
Found at index 5
If you for some reason can't use memcmp, create your own and use that instead in the example above:
int MemCmp(const void *s1, const void *s2, size_t len) {
const unsigned char* a = s1;
const unsigned char* b = s2;
for(;len; --len, ++a, ++b) {
if(*a < *b) return -1;
else if(*a > *b) return 1;
}
return 0;
}
kused instrsearch()? Why is it there?B[i+c]== Cis comparing acharto achar *. Save time, enable all warnings and let your good compiler give you rapid feedback. After fixing the warnings, re-post here if still needed.forloops. The outer loop provides an index into B which represents every possible starting position of the search string. The inner loop provides an index into C, which is used to compare each character, e.g.if (B[i+j] != C[j]) { /* mismatch, go to the next index in B */ }