Skip to study material
← Question index

QUESTION 40 · String Operations

Explain string concatenation with a capacity-checked example.

5 marks

Answer in brief

Concatenation appends one string to another. strcat places the source characters after the destination’s current text and writes a final terminator.

Basic form

strcat(destination, source);

Example explanation

destination starts as "Hello " in a 30-position array. source is "students". Their lengths are 6 and 8, so the result has length 14 and requires 15 positions. The check confirms the source fits in the remaining space, then strcat produces "Hello students".

Capacity check

After confirming the existing destination is a valid string in its array, remaining capacity for new non-null bytes is capacity - used - 1. Comparing the added length with that remainder avoids an unchecked sum. The sample uses sizeof destination where the actual array is visible.

Precautions

  1. The source and destination strings must not overlap.
  2. The destination must contain its original terminator before strcat is called.
  3. Do not append to a string literal or another non-writable target.
  4. Never assume the function enlarges an array automatically.

Time and space complexity

For destination length m and source length n, strcat first locates the existing end and then copies the new text, giving O(m + n) work in the usual analysis. Length checks add only another fixed number of scans. Auxiliary space is O(1) beyond the destination buffer. Repeatedly appending many tiny pieces can cause repeated rescanning of a growing prefix and become quadratic in total work.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#include <string.h>

int main(void)
{
    char destination[30] = "Hello ";
    const char *source = "students";
    size_t used = strlen(destination), added = strlen(source);
    if (added > sizeof destination - used - 1) { puts("Too long"); return 1; }
    strcat(destination, source);
    puts(destination);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Hello students

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 →