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;
}
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 2 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.
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.
Hardik chugh said:
8 years ago
Correct answer is OPTION B- invalid constant expression.
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.
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.
Mahalakshmi said:
4 years ago
@Rahul Agarwal.
Perfect explanation. Thank you.
Perfect explanation. Thank you.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers