Arrays & Strings
![Question 19, GATE 2025: A C program initializes char a[30]="@#Hello World!"; calls stringcopy(a,a+2); and prints a using printf("%s\n",a). The user-defined function is:
void stringcopy(char *s,char *t) { while (*t) *s++ = *t++; }
What is printed before the newline?
Options: A. @#Hello World!; B. Hello World!; C. ello World!; D. Hello World!d!.](../../../assets/questions/CS-2025-S2-Q19-1.webp)
Answer & solution
Official answer: D
Step through it (34 steps)
The source pointer begins at index 2, the H, and the destination begins at index 0. Initially the string occupies indices 0 through 13 and its null terminator is at index 14. The loop copies the 12 non-null characters “Hello World!” from source indices 2…13 into destination indices 0…11.
After the last exclamation mark is copied, t points at index 14. The condition *t is now zero, so the loop stops before copying that null terminator. Destination indices 12 and 13 were never overwritten and still contain the original d and !. The first terminating null remains at index 14. Thus the complete printed sequence is “Hello World!d!”, followed by the newline: D.
The key mistake in the function is failing to copy or append '\0'. This is an explicit forward-copy loop that reads two positions ahead of its writes, so previously overwritten bytes do not corrupt later reads. It should not be confused with calling the standard strcpy on overlapping arrays, which would have undefined behavior.
![Question 11, GATE 2015: What does this C program print?
#include <stdio.h>
int main() { char s1[7]="1234", *p; p=s1+2; *p='0'; printf("%s",s1); }
The assigned character is digit '0', not the null character '\0'. Options: (A) 12; (B) 120400; (C) 1204; (D) 1034.](../../../assets/questions/CS-2015-S3-Q11-1.webp)
![Question 33, GATE 2004: What is printed by this C fragment? Assume appropriate declarations/includes for i, strlen and printf.
char p[20];
char *s="string";
int length=strlen(s);
for(i=0;i<length;i++) p[i]=s[length-i];
printf("%s",p);
The %s format follows GFG. GateForum visibly prints a malformed alternate format rather than %s.
Options:
(A) gnirts
(B) string
(C) gnirt
(D) No output is printed](../../../assets/questions/CS-2004-Q33-1.webp)