0

I am trying to write a small program where I basically count the string length in a function but for some reason it is not outputting anything to the command line.

#include <stdio.h>

int search (char* string, char* substring){
    int length = 0;
    while(substring){
        substring++;
        length++;
    }
    return length;

}


int main(int argc, const char * argv[])
{
    char string1[] = "hello world";
    char* string = string1;
    char substring1[] = "world";
    char* substring = substring1;

    int a = search(string,substring);

    printf("%d", a);
    return 0;
}
0

3 Answers 3

4

You need to dereference it or you'll keep looping since there's no obvious way for substring to become 0.

while (*substring)
       ^

That's because you're not looking for the NULL pointer but rather for the NUL (\0) character.

Sign up to request clarification or add additional context in comments.

1 Comment

So simple yet so vital. Thank you ver much!
2

substring is a pointer, as long as it's pointing to somewhere memory, it will never be null (false).

Replace while(substring) with while(*substring) to look for the \0 character instead.

Comments

0

What's the point of "string" in the search function? You're using the substring variable, but not the string variable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.