C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Point Out Errors (Q.No. 11)
11.
Point out the error in the program?
#include<stdio.h>

int main()
{
    struct emp
    {
        char name[25];
        int age;
        float bs;
    };
    struct emp e;
    e.name = "Suresh";
    e.age = 25;
    printf("%s %d\n", e.name, e.age);
    return 0;
}
Error: Lvalue required/incompatible types in assignment
Error: invalid constant expression
Error: Rvalue required
No error, Output: Suresh 25
Answer: Option
Explanation:

We cannot assign a string to a struct variable like e.name = "Suresh"; in C.

We have to use strcpy(char *dest, const char *source) function to assign a string.

Ex: strcpy(e.name, "Suresh");

Discussion:
14 comments Page 1 of 2.

Rahul agarwal said:   8 years ago
Lvalue mean left side value.

Many time we face this type of error it come hear because trying to change a memory address value which is not possible.
When you declare "struct emp e;"
a memory is assign to "e" with size of "emp"--> (25*1+1*size of (int) +1*size of (float))
Amuse base address of "e" at memory is 2000 (in integer).
Then base address of "e.name" at memory is 2000 (in integer) .
Base address of "e.age" at memory is 2025 (in integer)

"e.name" will represent base address because of char array (e.name = 2000)
now at
e.name = "Suresh";
fist a temp memory will be assign to "Suresh" Asume 3000 (in integer)
and then trying to write a memory address to other memory address.
e.name = "Suresh"; ----> 2000=3000 ;

So it will we a volition.

You can never change memory adders you only can put a value in this.

Emad ibrahim said:   7 years ago
@All.

if we write.

#include<stdio.h>
int main()
{
struct emp
{
char name[25];
int age;
float bs;
};
struct emp e={"Suresh",15};
printf("%s %d\n", e.name, e.age);
return 0;
}

It will work successfully.

Alex said:   1 decade ago
We can't assign an array of character, because in this one char should go on each index that can not be possible by directly assigning.

For that we must use strcpy(e.Name, "Suresh");

Preethi said:   1 decade ago
What is this Lvalue error? I have seen it many time.

What does it mean actually?.

Can anyone explain me please ?

DileepChandra said:   10 years ago
Lvalue means left side value and here we are using string by declaring char. So there by it asks Lvalue.

Rajesh.T.K. said:   1 decade ago
In Find output of the program section, we have a question in which string is assigned. Why not here?

Hemant said:   1 decade ago
Can anyone explain this, why can't we assign an array of character with string ?

Sam910 said:   1 decade ago
@afiz - why is it B?

There is no problem in the structure assignment

Afiz said:   1 decade ago
Lvalue : left value, but this answer is wrong B is corrct

Hardik chugh said:   8 years ago
Correct answer is OPTION B- invalid constant expression.


Post your comments here:

Your comments will be displayed after verification.