-1

I tried to make a my own strlen function and when I tried to run it I always get +1 value to my counter. E.g. if it's 3 characters it would return 4 etc. Here is my code:

#include <stdio.h>
#define MAX 1000
void length(char string[MAX]){
    int i, counter = 0; 
    for(i=0;string[i]!='\0';i++){
       counter++;
    }
    printf("Your string has %d characters", counter);
}
int main(){
    char ch[MAX];
    printf("Enter a string: ");
    fgets(ch, MAX, stdin);
    length(ch);
}

Any tips for a beginner like me would also be appreciated thanks! :)

1 Answers1

1

From the fgets() docs:

Reads at most count - 1 characters from the given file stream and stores them in the character array pointed to by str. Parsing stops if a newline character is found, in which case str will contain that newline character, or if end-of-file occurs. [...]

AKX
  • 152,115
  • 15
  • 115
  • 172