In C, which function returns the length of a C-style string?

Enhance your programming skills with the RECF Programming Test. Features flashcards and multiple choice questions with hints and explanations. Prepare for success!

Multiple Choice

In C, which function returns the length of a C-style string?

Explanation:
The length of a C-style string is the number of characters before the terminating null character, not including the terminator. The standard way to obtain that length is to use the strlen function from string.h. strlen takes a pointer to the first character and scans the array until it encounters '\0', returning the count as a size_t. This gives the actual number of characters in the string. Using sizeof(name) doesn’t measure the string’s length; it tells you how many bytes are allocated for the array (or for the pointer, on some platforms), which often isn’t the same as the number of characters in the string. strnlen(name, n) can report a length up to a maximum n, which is useful for safety but isn’t the portable, standard way to get the string length. strlen_s is a bounds-checked variant available in some environments and isn’t portable across all C implementations.

The length of a C-style string is the number of characters before the terminating null character, not including the terminator. The standard way to obtain that length is to use the strlen function from string.h. strlen takes a pointer to the first character and scans the array until it encounters '\0', returning the count as a size_t. This gives the actual number of characters in the string.

Using sizeof(name) doesn’t measure the string’s length; it tells you how many bytes are allocated for the array (or for the pointer, on some platforms), which often isn’t the same as the number of characters in the string. strnlen(name, n) can report a length up to a maximum n, which is useful for safety but isn’t the portable, standard way to get the string length. strlen_s is a bounds-checked variant available in some environments and isn’t portable across all C implementations.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy