Skip to study material
← Question index

QUESTION 34 · String Operations

Explain the main string library functions and their precautions.

5 marks

Answer in brief

The string.h header declares common operations on null-terminated strings and memory. Each function still requires valid arguments and sufficient storage.

Main functions

  1. strlen(s) returns the number of bytes before the null terminator as size_t.
  2. strcpy(destination, source) copies the source and its terminator.
  3. strcat(destination, source) appends the source after the destination’s existing string.
  4. strcmp(a, b) compares two strings and returns a negative, zero or positive value.
  5. strchr(s, ch) locates the first matching character, or returns NULL when absent.

Capacity requirements

strcpy needs enough writable destination positions for source length plus one. strcat needs enough for both lengths plus one, and destination must already contain a valid string. These functions do not receive the destination’s capacity and cannot automatically grow it.

Overlap and bounded forms

strcpy and strcat require non-overlapping source and destination strings. For overlapping regions within one array, memmove is designed for moving a specified byte count safely. strncpy is not a general guarantee of termination: if the source is at least the specified count, the copied result is not automatically terminated.

Comparison and length

Use strcmp rather than == to compare text contents. Check only its result’s sign, not an assumed exact -1 or 1. Use %zu for the size_t returned by strlen. The length excludes the terminator, while required storage includes it.

Complexity

strlen and strcpy perform work proportional to the relevant string length. A single strcat must find the destination end and copy the source, giving O(d + s) work. strcmp examines a prefix until a difference or end is reached, up to O(min(m, n) + 1) byte comparisons. No growing auxiliary array is required by these basic operations.

Reference table

↔ Scroll horizontally on a small screen
String function requirements
FunctionPurposeKey requirement
strlenCount bytes before terminatorValid terminated source
strcpyCopy with terminatorEnough capacity; no overlap
strcatAppend sourceTerminated destination; enough space; no overlap
strcmpCompare contentsBoth sources terminated
strchrFind characterValid terminated source
memmoveMove specified byte countValid source/destination ranges; overlap allowed

Related exam questions

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

  • September/October 2021 · Q7(b) · 8 marks

    Describe string library functions with syntax and an example program.

    Paper P01 · page 1
  • March/April 2023 · Q4(a) · 5 marks

    Explain strcat and strcpy with examples.

    Paper P02 · page 1

View this category in the exam question bank →