In C programming (assume sizeof(int) = 2 bytes), what will this program print?
#include
void fun(char**);
int main()
{
char argv[] = {"ab", "cd", "ef", "gh"};
fun(argv);
return 0;
}
void fun(char p)
{
char t;
t = (p += sizeof(int))[-1];
printf("%s
", t);
}
Carefully analyze the pointer arithmetic on the char parameter and identify the string printed.
-
Aab
-
Bcd
-
Cef
-
Dgh
-
EUndefined behavior at runtime
Answer
Correct Answer: cd
Explanation
Introduction / Context:This question tests pointer arithmetic with pointer-to-pointer types in C. The function receives a char that points to the first element of an array of char* (C-strings). Understanding how pointer increments scale by the size of the pointed-to type is critical for predicting the printed output.
Given Data / Assumptions:
- sizeof(int) = 2 bytes (as stated).
- Array: argv = { "ab", "cd", "ef", "gh" }.
- p is a char** initially pointing to &argv[0].
- Expression: t = (p += sizeof(int))[-1].
Concept / Approach:In C, pointer arithmetic advances by the size of the pointed-to type, not by bytes you write in code. Since p is a char**, p += 2 moves two elements forward (two pointers), not two bytes. Then the [-1] index selects the element immediately before the new position.
Step-by-Step Solution:Start: p → &argv[0].Compute p += sizeof(int) → p += 2 → p now points to &argv[2].Index [-1] → *(p - 1) → argv[1].Assign t = argv[1] → t points to "cd".printf prints "cd".
Verification / Alternative check:You can mentally rewrite (p += 2)[-1] as *(p + 2 - 1) with p originally at element 0, giving element 1 → "cd".
Why Other Options Are Wrong:"ab" is argv[0]; "ef" is argv[2]; "gh" is argv[3]; none match the indexed location after the pointer math. "Undefined behavior" does not apply because indexing stays within the array bounds.
Common Pitfalls:Confusing sizeof(int) with raw byte offset on a pointer-to-pointer; in C, pointer arithmetic already scales by element size. Also, misreading [-1] as invalid; it is valid when the pointer already advanced.
Final Answer:cd