-4

The following code is for searching a string or character in another string :-

`

#include<stdio.h>
#include<string.h>

int strindex( char primary[] , char searchfor[]){

    int k;

    for(int i = 0 ; primary[i] != '\0' ; i++){
        for(int j = i , k = 0 ; (searchfor[k] != '\0') && (primary[j] == searchfor[k]) ; j++ , k++){
            ;
        }

    if( k > 0 && searchfor[k] == '\0'){
        return i;
        }

    }

    return -1; 
}

int line( char *str ){
    int i = 0;
    char c;

    for (;(c = getchar()) != '\n' && (c != EOF) ; i++){
        str[i] = c;
    }

    if( c = '\n') str[i] = '\n';
    str[++i] = '\0';

    return i;
}

int main(){

    char str1[100] , str2[100];

    int i ;

    puts("Enter the main string:-");
    line(str1);
    puts("Enter string to search for:-");
    line(str2);

    i = strindex(str1 , str2);

    if( i >= 0){
        printf("String found at index : %d \n",i);
    }else{
        puts("stirng not found.");
    }

    puts("");

    return 0;
}

`

The compile result :-

PS E:\Workspace\C> gcc p1.c
PS E:\Workspace\C> ./a.exe
Enter the main string:-
this is a demo text
Enter string to search for:-
demo
PS E:\Workspace\C>

I am using visual studio code , As we can see that the "if-else" and "print" statements after the function call are not being executed . I have tried a lot , but could not make it . Please someone help me and tell me where I am going wrong ??

1 Answers1

3
int k;
for (int j = i, k = 0; ...) { blahBlahBlah(); }
doSomethingWith(k);

That k in the for loop is not the k declared before it, it's a new variable that shadows (hides) the original. That's because using int inside the for loop is a new declaration for all variables following it.

Then, when it comes time to doSomethingWith(k), that's using the original k, as the other one has gone out of scope.

And, since that original k will have some arbitrary value, hilarity will ensue :-)

The quickest solution is probably to remove the declaration from the for statement:

int j, k;
for (j = i, k = 0; ...) { blahBlahBlah(); }
doSomethingWith(k);

In your case, that would be along the lines of:

int strindex(char *primary, char *searchfor) {
    int j, k;

    for (int i = 0; primary[i] != '\0'; i++) {
        for (j = i, k = 0; (searchfor[k] != '\0') && (primary[j] == searchfor[k]); j++, k++);
        if (k > 0 && searchfor[k] == '\0') return i;
    }
    return -1; 
}

As an aside, this is also a problem (in line()):

if (c = '\n') str[i] = '\n'; // First = should be ==, anyway.
str[++i] = '\0';

It preserves the newline character so that you would be looking for "demo\n" in "this is a demo text\n", which won't be found. Better to just use:

str[i] = '\0';

And, on top of that, c should be an int, not a char. That's because it has to cater for all possible char values and EOF.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953