QUESTION 27 · String Basics
What marks the end of a C string?
2 marksAnswer
A null character, written '\0', marks its end.
- It is different from the digit character '0'.
- A string with n non-null character bytes needs at least n + 1 array positions.
QUESTION 27 · String Basics
A null character, written '\0', marks its end.
QUESTION 28 · String Basics
A C string is a sequence of character bytes terminated by a null character. A character array is a string only when the required terminator is present within its valid storage.
char word[] = "Code";
/* elements: C, o, d, e, \0 */word contains five char elements, so sizeof word is 5 C bytes. Its string length is 4 because strlen counts characters before the terminator. A destination for four visible ASCII characters needs at least five char positions. The terminator occupies space even though it is not printed as part of the text.
char word[] = "Code"; creates a writable array initialised from the literal. const char *label = "Code"; creates a pointer to a string literal that must not be modified. The array and the pointer have different sizes and assignment rules.
Finding the length with strlen requires examining bytes until the terminator, giving O(n) work in the ordinary analysis. A known-index character read is O(1). These introductory examples process ordinary text bytes; a byte count is not necessarily the count of displayed Unicode characters in a multibyte encoding.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#include <string.h>
int main(void)
{
char word[] = "Code";
printf("Length = %zu, array bytes = %zu\n", strlen(word), sizeof word);
return 0;
}This example uses values already written in the program.
Length = 4, array bytes = 5Related questions in the string basics category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Differentiate a null-terminated string and a fixed-length string.
Paper P06 · page 1Compare character arrays and string literals. Explain strings as arrays of characters.
Paper P08 · page 1