Modifying a char array then attempting to reassign it: what does this program do? #include int main() { char str[] = 'Nagpur'; // writable array str[0] = 'K'; // modify first character → 'Kagpur' printf('%s, ', str); str = 'Kanpur'; // attempt to reassign an array variable printf('%s', str+1); return 0; }

C# Programming Strings Difficulty: Easy
Choose an option
  • A
    Kagpur, Kanpur
  • B
    Nagpur, Kanpur
  • C
    Kagpur, anpur
  • D
    Error
  • E
    Kagpur, agpur

Answer

Correct Answer: Error

Explanation

Introduction / Context:This focuses on the difference between a modifiable char array and the immutability of an array name as an lvalue. While you may modify the contents of a char array element by element, you cannot reassign the array variable itself to point to a different string literal after declaration.

Given Data / Assumptions:

  • str is defined as a char array initialized with 'Nagpur'.
  • str[0] = 'K' is valid, producing 'Kagpur'.
  • Attempting 'str = 'Kanpur';' is illegal because array names are not modifiable lvalues.

Concept / Approach:In C, an array variable is not a pointer variable that you can reassign; it represents a fixed block of memory. You may copy into it with functions like strcpy, but assigning a new literal to the array variable is a compile-time error.

Step-by-Step Solution:

str declared as array → valid modification via str[0] = 'K'.printf prints 'Kagpur, '.Next line tries to assign to the array name → violates C constraints → compilation fails.

Verification / Alternative check:If you replace the invalid assignment with strcpy(str, 'Kanpur'); then the final print could show 'anpur' from str+1.

Why Other Options Are Wrong:

Outputs implying successful reassignment ('Kagpur, Kanpur' or 'Kagpur, anpur') would require copying or using a pointer variable, not an array.'Nagpur, Kanpur': ignores the earlier modification.

Common Pitfalls:Confusing arrays with pointers; trying to reassign arrays instead of copying data into them.

Final Answer:Error.

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