w3resource

C Language: Custom strlen() function

C - Implementing a custom strlen() function

The strlen() function is used to get the length of a string excluding the ending null character.
Here's an implementation of a custom strlen() function:

Code:

#include <stdio.h>

size_t custom_strlen(const char* str) {
    size_t len = 0;
    while (*str != '\0') {
        len++;
        str++;
    }
    return len;
}

int main() {
    char str[] = "C Snippets";
    size_t len = custom_strlen(str);
    printf("Length of the string is %lu\n", len);
    return 0;
}

Output:

Length of the string is 10

In the custom_strlen() function, we start with len = 0 and iterate through the string until we reach the null character '\0'. In each iteration, we increment "len" and move the pointer to the next character. Finally, we return the length of the string.

In the main() function, we declare a character array str with the string "C Snippets" call custom_strlen() to find its length, and print the length.

Contribute your code and comments through Disqus.



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

C Programming - How do you pass a function as a parameter in C?

Declaration

A prototype for a function which takes a function parameter looks like the following:

void func ( void (*f)(int) );

This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:

void print ( int x ) {
  printf("%d\n", x);
}

Function Call

When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:

func(print);

would call func, passing the print function to it.

Function Body

As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:

for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
  print(ctr);
}

Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:

void func ( void (*f)(int) ) {
  for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
    (*f)(ctr);
  }
}

Ref : https://bit.ly/3skw9Um