How to get string length in function

Viewed 57

How can I get the length of the buffer in the function using pointers?

#include <stdio.h>
#include <stdlib.h>

void fun(char *(buffer))
{
    printf(strlen(buffer));
}

int main()
{
    char buffer[] = "Hello";
    fun(&buffer);

    return 0;
}
1 Answers

You need to include the header

#include <string.h>

then in the function to write

void fun(char *buffer)
{
    printf( "%zu\n", strlen( buffer ) );
}

or

void fun(char *buffer)
{
    size_t n = strlen( buffer );
    printf( "%zu\n", n );
}

and at last to call the function like

fun( buffer );

If you need to get the length of the passed string within the function yourself without using the standard string function strlen then the function can look like

void fun(char *buffer)
{
    const char *p = buffer;

    while ( *p ) ++p;
    size_t n = p - buffer;

    printf( "%zu\n", n );
}
Related