Ashish Agarwal Ashish Agarwal - 4 months ago 14
C Question

Find length of string in C (without using strlen)

The code below does not print anything -

int main() {

char *input = "This is a string";
find_length(input);
return 0;

}
void find_length(char *input){

printf("%s", input);
int length = 0;
while(input[length]!='\0');
{
length++;
printf("%i", length);
}

}

Answer

You have an extra semicolon behind your loop:

while(input[length]!='\0');
                          ^ does not belong here!!!

So it is stuck in an infinite loop. Get rid of it.


Furthermore, there could be stream buffering. Try adding some \n. Or call fflush(stdout) to flush the output stream.

void find_length(char *input){

    printf("%s\n", input);
    int length = 0;
    while(input[length]!='\0')  //  remove ;
    {
        length++;
        printf("%i\n", length);
    }

}