Pointer types and %s in printf: what happens when you pass &str + 2 (a pointer to beyond the array) to %s? #include<stdio.h> int main() { char str[25] = "CuriousTab"; printf("%s ", &str + 2); return 0; } Select the most accurate outcome.

Difficulty: Medium

Correct Answer: Garbage value

Explanation:


Introduction / Context:
This question highlights undefined behavior from passing an incorrect pointer type to printf with %s. The %s specifier expects a char* that points to a valid, null-terminated byte string. Supplying &str + 2 (type char ()[25] advanced by two arrays) is not a valid char pointer to a string.



Given Data / Assumptions:

  • str is an array of 25 chars initialized to "CuriousTab".
  • &str has type char ()[25], a pointer to the entire array object.
  • &str + 2 points two arrays past the object, i.e., far beyond valid storage.
  • printf("%s", ...) expects a pointer of type char to a readable null-terminated sequence.


Concept / Approach:
When calling variadic functions, the argument types must match the format string. Here they do not. The value passed is a pointer-to-array (after arithmetic) rather than a char*. As a result, behavior is undefined: the program may crash, print garbage, or appear to print some bytes coincidentally.



Step-by-Step Solution:
Take address of array: &str → char ()[25].Add 2: &str + 2 → points beyond the valid array object.printf expects char: treats the mismatched pointer as if it were a char*.Reading memory at that bogus address yields undefined behavior (often garbage output or a fault).



Verification / Alternative check:
Correct usage would be printf("%s\n", str); or printf("%s\n", &str[0]); both produce "CuriousTab". Using &str + 2 is invalid regardless of platform.



Why Other Options Are Wrong:
Error / No output: The code typically compiles; runtime behavior is not predictably an error or silence."diaCURIOUSTAB": a specific string cannot be guaranteed; undefined behavior has no reliable outcome.Reliably prints "CuriousTab": only true with the correct pointer, not with &str + 2.



Common Pitfalls:
Confusing char* with char (*)[N]; doing pointer arithmetic on &str; forgetting that varargs require exact matching types for format specifiers.



Final Answer:
Garbage value

More Questions from Strings

Discussion & Comments

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