Discussion
Consider the following C program:
#include \(\lt\)stdio.h\(\gt\)
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?
Answer: D
The program prints Hello World!d!.
The array holds "@#Hello World!": 14 characters in a[0] to a[13], then the terminator in a[14]. The call stringcopy(a, a + 2) copies from the third character onwards into the start of the array.
The loop while(*t) *s++ = *t++; stops when *t is the terminator, without copying it. So it copies the 12 characters 'Hello World!' into a[0] to a[11], and a[12] and a[13] keep their old values, 'd' and '!'. The original terminator at a[14] is untouched.
printf then prints a[0] to a[13]: Hello World!d!. 'Hello World!' alone would be printed only if the terminator were copied too. The original string and 'ello World!' would need different copy offsets.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development