'i wrote a c program of creating a string length counter in C but the code isnt running
//write a c program to make your own version of strlen from <string.h>
#include<stdio.h>
int strlength(char * str){
char *ptr=str;
int len=0;
while(*ptr!='\0'){
len++;
str++;
}
return len;
}
int main(){
char str[]="bishal";
int l=strlength(str);
printf("the length of the string is %d",l);
return 0;
}
this was the code i was writing and i dont know why but my text editors wont run it for me plus i cannot see any error on the screenenter image description here
the only error i can see is when i try to run the same in an online compiler , the error looks like this /tmp/zcp4rImwpV.o
if anyone knows the answer to my question then please help.
Solution 1:[1]
Instead of incrementing str in your function strlength, increment ptr. Your while loop is running infinitely because ptr never reaches '\0'. Like this:
#include<stdio.h>
int strlength(char * str){
char *ptr=str;
int len=0;
while(*ptr!='\0'){
len++;
ptr++;
}
return len;
}
int main(){
char str[]="bishal";
int l=strlength(str);
printf("the length of the string is %d",l);
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | onapte |
