ProgrammingVery hardProduct company OA

What is printed?

What is printed?
char a[8] = "abcdefg";
memmove(a + 2, a, 4);
char b[6] = "XXXXX";
strncpy(b, "hi", 4);
char c[4];
strncpy(c, "wxyz", 4);
printf("%s %zu %c %.4s", a, strlen(b), b[4], c);
  1. A. ababcdg 2 X wxyz
  2. B. ababafg 2 X wxyz
  3. C. ababcdg 5 X wxyz
  4. D. ababcdg 2 \0 wxy

Correct answer: A. ababcdg 2 X wxyz

memmove behaves as if it copied through a temporary, so overlapping is safe: positions 2–5 receive the ORIGINAL a, b, c, d → ababcdg (a naive forward memcpy-style loop would give ababafg… that is the trap, and calling memcpy here would be undefined). strncpy(b, "hi", 4) writes 'h', 'i' and then pads with '\0' up to 4 bytes, so strlen is 2 while b[4] is still 'X'. strncpy(c, "wxyz", 4) writes NO terminator, which is why the code prints it with %.4s.

More C Programming questions

Exams that ask this topic