c - union memory allocation :: stores more content than allocated memory -
i have defined union
union person { int roll; char fname[10]; char lname[20]; }p1; and sizeof(p1)=20 bytes. while storing content in p1 storing more 20 chars.
void main() { printf("\n size of union %zu\t",sizeof(p1)); printf("\n come in details here :\t"); scanf("%d",&p1.roll); scanf("%s",p1.fname); scanf("%s",p1.lname); printf("\n union contains \n"); printf("\n roll no :: \t %d",p1.roll); printf("\n fname :: \t %s ",p1.fname); printf("\n laname :: \t %s\n",p1.lname); } when give input more 20 char,still stored.
when give input more 20 char,still stored.
of course of study is. why wouldn't it? handed scanf pointer , said "write many chars here perchance wish!"
scanf("%9s",p1.fname); scanf("%19s",p1.lname); that prevent scanf overrunning buffer. note i've subtracted 1 each length, scanf needs write nul terminator well.
now, next problem: why using union? union used provide different views of same data. writing 1 fellow member trashes contents of others. unions used rarely, in constrast structs.
if want store multiple related pieces of information, utilize struct.
struct person { int roll; char fname[10]; char lname[20]; } p1; c memory-management struct unions
No comments:
Post a Comment