Question

Consider the following C program:

#include <stdio.h>

void stringcopy(char *, char *);

int main(){
        char a[30] = "@#Hello World!";
        stringcopy(a, a + 2);
        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?

Choose one option
Official answer and solution
Official answer
D
From
Official GATE 2025 answer key

Solution

Trace the overlapping in-place character copy and observe that while(*t) stops before copying the null terminator '\0'.

  1. Initially, a contains the 14-character string "@#Hello World!" at indices 0..13, followed by '\0' at index 14.
  2. stringcopy(a, a + 2) copies the 12 characters of "Hello World!" from indices 2..13 into indices 0..11.
  3. When t reaches index 14 (*t == '\0'), the while(*t) loop terminates without copying '\0' into a[12].
  4. Thus a[12] and a[13] retain their original characters 'd' and '!', followed by '\0' at a[14], so printf("%s\n", a) prints Hello World!d!.
Final answer

Option (D)

Common trap

Assuming stringcopy copies the terminating null character '\0' at index 12.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2025 Computer Science and Information Technology - Session 2 (CS2)
Question
19 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.