Consider the following C program: #include <stdio.h> void stringcopy(char *,…

2025

Consider the following C program:

#include <stdio.h>

void stringcopy(char *, char *);

int main() {
    char a[30] = "@#Hello World!";
    stringcopy(a, a + 2); // Copy from a+2 to a
    printf("%s\n", a);
    return 0;
}

void stringcopy(char *s, char *t) {
    while (*t)
        *s++ = *t++;
}

Which ONE of the following will be the output of the program?

  1. A.

    @#Hello World!

  2. B.

    Hello World!

  3. C.

    ello World!

  4. D.

    Hello World!d!

Attempted by 54 students.

Show answer & explanation

Correct answer: D

Answer: Hello World!d!

Key insight: The function copies characters from a+2 into a but does not copy the terminating null byte, so leftover characters after the copied region remain in the array and become part of the printed string.

  • Start: the array a initially contains: index 0='@', 1='#', 2='H', 3='e', 4='l', 5='l', 6='o', 7=' ', 8='W', 9='o', 10='r', 11='l', 12='d', 13='!', 14='\0'.

  • stringcopy(a, a+2) sets s = a (index 0) and t = a+2 (index 2). Each loop iteration copies *t to *s and increments both pointers, so characters at indices 2..13 are copied into positions 0..11.

  • After copying, a[0..11] contain 'H','e','l','l','o',' ','W','o','r','l','d','!'. The loop then stops when *t is the original terminating '\0' at index 14, but that '\0' is not written into the destination because the code stops before copying it.

  • Indices 12 and 13 remain their original characters 'd' and '!', so the characters from index 0 up to the original null produce the string "Hello World!d!".

Therefore the program prints: Hello World!d!

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir