Machine-translated by Google. Questions are authored in English.
Top

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?

  • A.@#Hello World!
  • B.Hello World!
  • C.ello World!
  • D.Hello World!d!

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.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.