Skip to study material
← Question index

QUESTION 28 · String Basics

Explain C strings, null termination and character arrays.

5 marks

Answer in brief

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.

Declaration

char word[] = "Code";
/* elements: C, o, d, e, \0 */

Length and capacity

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.

Array versus pointer

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.

Important examples

  1. char a[4] = {'C', 'o', 'd', 'e'} has no terminator and must not be used as a string by strlen or puts.
  2. An empty string contains a terminator at its first position and has length zero.
  3. The null character is not the same as a null pointer.

Complexity and text

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.

Diagram or flowchart

CodeBhavya illustration of string layout.
Explain C strings, null termination and character arrays. · Download diagram

C program and output

/* 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;
}

Sample input and output

This example uses values already written in the program.

Output

Length = 4, array bytes = 5

Related exam questions

Related questions in the string basics category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September 2023 · Q4(a) · 5 marks

    Differentiate a null-terminated string and a fixed-length string.

    Paper P06 · page 1
  • January/February 2024 · Q4(b) · 6 marks

    Compare character arrays and string literals. Explain strings as arrays of characters.

    Paper P08 · page 1

View this category in the exam question bank →