Reputation: 1449
I have defined a union as
union person
{
int roll;
char fname[10];
char lname[20];
}p1;
And the sizeof(p1)=20 bytes. but while storing the content in p1 its storing more than 20 chars.
void main()
{
printf("\n The size of the union is %zu\t",sizeof(p1));
printf("\n Enter the details here :\t");
scanf("%d",&p1.roll);
scanf("%s",p1.fname);
scanf("%s",p1.lname);
printf("\n The union contains are \n");
printf("\n The roll no is :: \t %d",p1.roll);
printf("\n The fname is :: \t %s ",p1.fname);
printf("\n The laname is :: \t %s\n",p1.lname);
}
when i give input more than 20 char,still its stored.
Upvotes: 0
Views: 66
Reputation: 10224
To add to Jonathon's answer, I would point out that the reason more than 20 chars is stored is because scanf
has no idea about your union.
When you declare the union
union person
{
int roll;
char fname[10];
char lname[20];
}p1;
and say
scanf("%s",p1.lname);
all scanf
sees is that you have it a char *
to store the string into. It doesn't see a char[20]
.
In other words, the additional information that you as a programmer know - that p1.lname
is only 20 characters - is not visible to scanf
.
Generally, in C, it's up to you as the programmer to ensure that you don't go around reading or writing more data than your buffers can handle.
Upvotes: 1
Reputation: 137438
when i give input more than 20 char,still its stored.
Of course it is. Why wouldn't it? You handed scanf
a pointer and basically said "write as many chars here as you possibly wish!"
scanf("%9s",p1.fname);
scanf("%19s",p1.lname);
That will prevent scanf
from overrunning the buffer. Note that I've subtracted one from each length, as scanf
needs to write a NUL terminator as well.
Now, the next problem: Why are you using a union
? A union is used to provide different views of the same data. Writing to one member effectively trashes the contents of all others. union
s are used very rarely, in constrast to struct
s.
If you want to store multiple related pieces of information, use a struct
.
struct person
{
int roll;
char fname[10];
char lname[20];
} p1;
Upvotes: 3