I want a user defined function which is equivalent to strlen() function in C. In the below program it does the same function as strlen() but it has a limit to it. How can I make it count any length of text.
#include <stdio.h>
#include <conio.h>
void main()
{
int len(char *);
char s[20];
int l;
printf("Enter a string: ");
gets(s);
l=len(s);
printf("length of string is =%d",l);
getch();
}
int len(char *t)
{
int count=0;
while(*t!='\0')
{
count++;
t++;
}
return(count);
}
I think your “limit” is because you use
gets()on a buffer of 20 bytes. You will experience issues due to a buffer overflow. Exactly what happens when you do that is not entirely predictable.If you fix that, I think your function will work as you expect it to. (Read the other people’s answers for insight on your length function.)