chakeda chakeda - 2 months ago 6
C Question

IndexOf function not working in C

I'm new to C pointers and I'm trying to write a program similar to a high level programming language's String.IndexOf() function.

Based on String.indexOf function in C, I've got it working:

int main() {
int index;
char* source = "test string";
char* found = strstr( source, "in" );
if (found != NULL) {
index = found - source;
}

printf("%d\n", index); // prints 8.
return 0;
}


But when I try to use this as a function, I always get 0. (For example, "Hello World" for the first string then "World" will print "0" and not the expected value "6").

Basically, the first line from stdin is the "source" (or "haystack") string and the following lines will be the "needle".

// includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// globals
char master[120];

// returns the index of the substring
int substr(char* needle) {

int index;
char* found = strstr( master, needle );
if (found != NULL) {
index = found - needle;
}

printf("%d\n", index);
return index;

}

int main() {
char input[120];
int timesCalled = 0;

while(fgets(input, 120, stdin)) {
timesCalled++;
if (timesCalled == 1) {
strcpy(master, input);
} else {
substr(input);
}
}

if (timesCalled == 0) {
fprintf(stderr, "Master String is empty");
return 1;
}

return 0;
}


What's going on here? Does the pointer of "master" change when it's set as a global variable? Does the pointer of "input" change when it's passed as a parameter? Why does it work in the procedural version?

Any input is appreciated.

EDIT!

I've changed the line
strcpy(input, master)
to
strcpy(master, input)
and I still get the same result!

Answer

Since you want the index in string master, what you need to do instead of

if (found != NULL) {
    index = found - needle;
}

is to replace index = found - needle with index = found - master.