QUESTION 43 · String Operations
Does a string length include the null terminator?
2 marksAnswer
No. It counts the bytes before the terminator.
- Start a counter at zero.
- Increase it while the current byte is not '\0'.
QUESTION 43 · String Operations
No. It counts the bytes before the terminator.
QUESTION 44 · String Operations
A manual length function scans from the first character until the terminating null character is reached.
For "Code", index 0 contains C, index 1 contains o, index 2 contains d and index 3 contains e. Each adds one to length. At index 4 the null character is found, so the returned length is 4.
size_t is suitable for an object or string size. The sample obtains its declaration through stddef.h and prints it with %zu. It does not assume every valid string length fits int.
The pointer must identify a valid string with a terminator reachable inside its permitted object. Without that terminator, the loop could read out of bounds; using a pointer or a library function does not repair an invalid string. A null pointer is not an empty string and cannot be passed here.
An empty string starts with the terminator, so the loop runs zero times and returns zero. Spaces are counted like other non-null bytes. A multibyte encoded character may occupy several bytes, so this result is a byte-string length rather than a universal displayed-character count.
For n non-null bytes, the loop makes n increments and a final stopping test. Time is O(n). It stores only the counter and pointer parameter, giving O(1) auxiliary space. The source is not modified or duplicated.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#include <stddef.h>
size_t text_length(const char *s)
{
size_t length = 0;
while (s[length] != '\0') { ++length; }
return length;
}
int main(void)
{
printf("Length = %zu\n", text_length("Code"));
return 0;
}This example uses values already written in the program.
Length = 4Related questions in the string functions category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Describe string library functions with syntax and an example program.
Paper P01 · page 1Explain strcat and strcpy with examples.
Paper P02 · page 1