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?
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'.
- Initially,
acontains the 14-character string"@#Hello World!"at indices0..13, followed by'\0'at index14. stringcopy(a, a + 2)copies the 12 characters of"Hello World!"from indices2..13into indices0..11.- When
treaches index14(*t == '\0'), thewhile(*t)loop terminates without copying'\0'intoa[12]. - Thus
a[12]anda[13]retain their original characters'd'and'!', followed by'\0'ata[14], soprintf("%s\n", a)printsHello 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.