Which expression returns the length of a C-style string stored in a character array named name?

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

Multiple Choice

Which expression returns the length of a C-style string stored in a character array named name?

Explanation:
C-style strings store characters up to a terminating null character, so the length is the count of characters before that '\0'. The standard way to obtain this length is to use the function that scans the string until it finds the null terminator. That function returns exactly how many characters are in the string, not how much space the array has. sizeof(name) would give the total number of elements in the array (its capacity), not how many characters are actually used by the string, and if name were passed to a function it would decay to a pointer, making sizeof refer to the pointer size instead of the array size. length(name) isn’t a standard function for measuring C-style strings. Constructing a std::string from name and then taking its length would work, but it’s indirect and involves creating a temporary object and a copy, rather than directly querying the stored string length.

C-style strings store characters up to a terminating null character, so the length is the count of characters before that '\0'. The standard way to obtain this length is to use the function that scans the string until it finds the null terminator. That function returns exactly how many characters are in the string, not how much space the array has.

sizeof(name) would give the total number of elements in the array (its capacity), not how many characters are actually used by the string, and if name were passed to a function it would decay to a pointer, making sizeof refer to the pointer size instead of the array size.

length(name) isn’t a standard function for measuring C-style strings. Constructing a std::string from name and then taking its length would work, but it’s indirect and involves creating a temporary object and a copy, rather than directly querying the stored string length.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy