How can the length of a character array in the C langua…

In C language, character arrays are stored in the form of strings, with the character ‘\0’ used as the terminator. To determine the length of a character array, you can use the strlen() function from the C standard library. The prototype of this function is as follows:

size_t strlen(const char *str);

The function takes a character pointer as a parameter and returns the length of the string (excluding the ending ‘\0’ character).

For example, let’s say we have a character array called str, we can use the strlen() function to get its length.

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello, World!";
    size_t length = strlen(str);
    
    printf("Length of str: %zu\n", length);
    
    return 0;
}

The output is:

Length of str: 13

Caution: Before using the strlen() function, make sure that the string in the character array is already ending with ‘\0’, otherwise it may result in unpredictable outcomes.

bannerAds