C strings copy loop: which statement must be added to properly terminate the destination so that it prints "CuriousTab"? #include<stdio.h> int main() { char s[] = "CuriousTab"; char t[25]; char *ps, *pt; ps = s; pt = t; while (*ps) *pt++ = *ps++; /* Add a statement here */ printf("%s ", t); return 0; }

Difficulty: Easy

Correct Answer: *pt = '\0';

Explanation:

Introduction / Context:This question addresses proper string handling in C. The loop manually copies characters from source s to destination t using pointers. To make t a valid C string, it must be null-terminated.

Given Data / Assumptions:

  • Copy loop stops when *ps is zero (the null terminator in s is not copied).
  • pt points to the first unwritten position in t after the loop.
  • printf("%s", t) expects t to be a null-terminated string.

Concept / Approach:C strings use a trailing null byte '\0' to mark the end. The loop copies only nonzero characters; after the loop we must explicitly write '\0' at the current destination location. Failing to do so yields undefined behavior when printing.

Step-by-Step Solution:Initialize ps to s and pt to t.While *ps is nonzero, copy and advance: *pt++ = *ps++.After loop, ps points to '\0' in s, pt points to next position in t.Write terminator: *pt = '\0'; so that t contains "CuriousTab\0".printf("%s", t) now prints “CuriousTab”.

Verification / Alternative check:Using strcpy(t, s) would both copy and null-terminate. Alternatively, copy the null explicitly inside the loop with a do/while version that copies the terminator.

Why Other Options Are Wrong:Empty character literal is invalid. Assigning '\0' to the pointer variable pt (not *pt) corrupts the pointer value. '' inserts a newline, not a terminator. Copying one more character without ensuring '\0' may still omit termination.

Common Pitfalls:Confusing pointer value vs. pointed-to value; forgetting to write the terminator when manually copying strings.

Final Answer:*pt = '\0';

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion