w3resource

C mblen() function

C mblen() function - Get number of bytes in a character

Syntax mblen() function

int mblen(const char *str, size_t n)

The mblen() function is used to get the length in bytes of the multibyte character pointed to by string. n represents the maximum number of bytes examined.

Parameters mblen() function

Name Description Required /Optional
str Address of a multibyte-character byte sequence. Required
n This is the maximum number of bytes to be checked for character length. Required

Return value from mblen()

If string is NULL, the mblen() function returns:

  • A non-zero value indicates that the active locale supports mixed-byte strings.The function initializes the state variable.
  • Zero otherwise.

If string is not NULL, mblen() returns:

  • A non-zero value indicates that the active locale supports mixed-byte strings. The function initializes the state variable.
  • Zero otherwise.

Example: mblen() function

The following example shows the usage of mblen() function.

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

int main( void )
{
    int      i;
    char    *mbstr = (char *)malloc( sizeof( char ) );

    i = mblen( mbstr, MB_CUR_MAX );
    printf( "Length in bytes of multibyte character %x: %u\n", *mbstr, i );

    mbstr = NULL;
    i = mblen( mbstr, MB_CUR_MAX );
    printf( "Length in bytes of NULL multibyte character %x: %u\n", mbstr, i );
}

Output:

Length in bytes of multibyte character ffffff80: 1
Length in bytes of NULL multibyte character 0: 0

C Programming Code Editor:

Previous C Programming: C ldiv()
Next C Programming: C mbstowcs()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
{
    ptr = 0;// oops, I meant *ptr = 0
}

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q