C programming — find the error in assigning to a char array member of a struct.
#include
int main()
{
struct emp
{
char name[25];
int age;
float bs;
};
struct emp e;
e.name = "Suresh"; /* assignment to array member */
e.age = 25;
printf("%s %d", e.name, e.age);
return 0;
}
What is the correct diagnosis?
-
AError: Lvalue required/incompatible types in assignment
-
BError: invalid constant expression
-
CError: Rvalue required
-
DNo error, output: Suresh 25
Answer
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