Home > Back-end >  I want to make my own version of (strlen) function...but why i am getting error
I want to make my own version of (strlen) function...but why i am getting error

Time:09-07

#include <stdio.h>

void strlen(char *ptr);

int main()
{
    char string[] = "david";
    int a = strlen(string);

    printf("Number of characters is %d", a);
    return 0;
}

void  strlen(char *ptr)
{
    int count = 0;
    while (*ptr != '\0')
    {
        count  ;
        ptr  ;
    }
    return count;
}

CodePudding user response:

to make my own version of (strlen) function

OP's compiler is rightly complaining about return value to a void function.

Use the standard's size_t strlen(const char *s); signature with a non-void return.

int will handle the length of most strings. size_t handles all strings and is the type used by many C library functions for sizing and string length.

// void  strlen(char *ptr)
size_t strlen(const char *ptr) 
{
    // int count = 0;
    size_t count = 0;
    while (*ptr != '\0')
    {
        count  ;
        ptr  ;
    }
    return count;
}

Usage

//int a = strlen(string);
//printf("Number of characters is %d", a);
size_t a = strlen(string);
printf("Number of characters is %zu\n", a);

Candidate simplification:

size_t strlen(const char *s) {
  const unsigned char *us = (const unsigned char *) s;
  while (*us) {
    us  ;
  }
  return (size_t)(us - (const unsigned char *) s);
}

Pedantic: Works well with rare signed non-2's complement too. OP's code can errantly stop on -0.

CodePudding user response:

Your strlen function is defined as void, meaning it won't return anything. However, you are expecting to use the return value, and your function tries to return a value.

You need to define it as int strlen(char *ptr), or even better, int strlen(const char *ptr) because you are not modifying the contents of ptr.

CodePudding user response:

You need to understand that you need only one condition to make your strlen() is to know that any string is ended with \0 so by using this information you can go through a while loop until you str[i] == '\0' that means you counted all characters in the string.

Example

#include <stdio.h>

int ft_strlen(char *str)
{
    int  i = 0;
    while (str[i] != '\0')
        i  ;
    return (i);
}

int main() {
    printf("%d", ft_strlen("Hello world"));
}

I recommend running this example on this website to understand the code more by yourself pythontutor.com

  •  Tags:  
  • c
  • Related