C programming — find the error in assigning to a char array member of a struct.\n\n#include<stdio.h>\n\nint main()\n{\n struct emp\n {\n char name[25];\n int age;\n float bs;\n };\n\n struct emp e;\n e.name = "Suresh"; /* assignment to array member */\n e.age = 25;\n\n printf("%s %d", e.name, e.age);\n return 0;\n}\n\nWhat is the correct diagnosis?

Difficulty: Easy

Correct Answer: Error: Lvalue required/incompatible types in assignment

Explanation:


Introduction / Context:
In C, arrays are not assignable after declaration. Initializing a char array with a string literal is allowed at declaration time, but assigning a string literal to an existing array variable is not permitted. This question checks that rule within a struct context.


Given Data / Assumptions:

  • struct emp has name as char name[25].
  • After creating e, code attempts e.name = "Suresh".


Concept / Approach:
Array identifiers decay to pointers in expressions but arrays themselves cannot be assigned to. To copy text into a char array, use library functions such as strcpy or strncpy, or read into it via scanf/gets (unsafe)/fgets with care.


Step-by-Step Solution:

1) e.name has type array of 25 char. Arrays are non-assignable.2) "Suresh" is a string literal of type array of char (const in modern practice).3) e.name = "Suresh"; violates assignment rules and causes a compile-time error.4) Correct approach: strcpy(e.name, "Suresh"); or initialize: struct emp e = {"Suresh", 25, 0.0f};


Verification / Alternative check:
Replacing the assignment with strcpy or an initializer compiles and runs, printing "Suresh 25".


Why Other Options Are Wrong:

  • Invalid constant expression / Rvalue required: Not the precise rule; the issue is that arrays are not assignable.
  • No error: The compiler rejects the assignment.


Common Pitfalls:
Confusing array assignment with pointer assignment. A char * can be assigned to point to a literal; a char[] cannot be assigned after declaration.


Final Answer:
Error: Lvalue required/incompatible types in assignment

More Questions from Structures, Unions, Enums

Discussion & Comments

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