C - String String Length


strnlen_s() function returns the length of a string.

It requires two arguments: the address of the string, which is the array name for a one-dimensional char array, and the size of the array.

The function returns the length of the string as an integer value of type size_t.

If the first argument is NULL, 0 will be returned.

If the array does not contain a \0 character within the number of elements specified by the second argument, the second argument value will be returned for the length of the string.


#define __STDC_WANT_LIB_EXT1__ 1     // Make optional versions of functions available
#include <string.h>                  // Header for string functions
#include <stdio.h>

int main(void)
  char str[][70] = {
    "test.",//from   ww  w.ja v  a 2 s. c  o  m
    "test test.",
  unsigned int count = 0;                              // Length of a string
  unsigned int strCount = sizeof(str) / sizeof(str[0]);  // Number of strings
  printf("There are %u strings.\n", strCount);

  // find the lengths of the strings
  for (unsigned int i = 0; i < strCount; ++i)
    printf("The string:\n    \"%s\"\n contains %zu characters.\n",
      str[i], strnlen_s(str[i], sizeof(str[i])));
  return 0;


The for loop iterates over the first dimension of the two-dimensional str array so it selects each string.

The third argument to printf() calls the strnlen_s() function to obtain the length of the string in str[i].

Applying the sizeof operator to str[i] provides the second argument value for strnlen_s().

Related Topics