Skip to study material
← Question index

QUESTION 36 · String Operations

Explain string initialisation, pointer assignment and copying into a character array.

5 marks

Answer in brief

A string can be used to initialise a character array, but replacing that array’s contents later requires copying characters into its writable storage.

Initialisation

char destination[20] = "Hello";

Copy after declaration

strcpy(destination, source) copies the characters and terminator when the destination is large enough and the regions do not overlap. The sample checks strlen(source) against sizeof destination before copying. It then prints the new contents C programming.

Pointer assignment

With const char *p = "Hello"; and p = "C";, only the pointer value changes. No characters are copied into the earlier string. This is valid pointer reassignment to another literal, but the literals themselves must not be modified.

Capacity example

A source of length 13 needs 14 char positions including the terminator. A 20-position destination can hold it. The comparison uses source length < destination capacity, not <=, because one position is reserved for the terminator.

Precautions

Do not apply sizeof destination as a capacity calculation when destination is merely an adjusted array parameter; pass the capacity separately. Do not assume strncpy always makes a usable string. If a manual copy is used, ensure it copies or writes the terminator too.

Complexity

Checking the length scans n source bytes, and copying scans them again. The total remains O(n), since a fixed number of linear passes is still linear. The copy writes into an existing buffer, with O(1) auxiliary space beyond that destination.

C program and output

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

int main(void)
{
    char destination[20] = "Hello";
    const char *source = "C programming";
    if (strlen(source) >= sizeof destination) { puts("Too long"); return 1; }
    strcpy(destination, source);
    puts(destination);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

C programming

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 →