Function that receives a string as a parameter and returns the length of that string | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Function that receives a string as a parameter and returns the length of that string

I try to create a function to return the length of the string but somehow it doesn't work! ' could you please help me check it? Here is the code : #include <stdio.h> int my_strlen(char *s){ int length =0; while(*s !='\0'){ s++; length ++; } return x; } int main() { printf("------------------------\n"); my_strlen("abcd") ; }

25th Nov 2020, 9:19 PM
Ticcher Leonar
Ticcher Leonar - avatar
3 Answers
+ 4
As Angelo said, x is not declared, but you also are not printing the value returned by my_strlen. And if you want you can use a more concise for loop instead of the while. https://code.sololearn.com/cdHTM971xk10/?ref=app
25th Nov 2020, 9:34 PM
Davide
Davide - avatar
+ 3
You haven't defined x You probably meant: return length;
25th Nov 2020, 9:21 PM
Angelo
Angelo - avatar
0
#include <stdio.h> #include <string.h> int my_strlen(char *s){ int length = 0; while(*s++) length++; return length; } int main() { printf("%d", my_strlen("abcd")); return 0; } // or int my_strlen(char *s){ int i=0; for(; *s++; i++); return i;
25th Nov 2020, 10:42 PM
rodwynnejones
rodwynnejones - avatar