By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,918 Members | 2,225 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,918 IT Pros & Developers. It's quick & easy.

structure

P: 18
how a structure is different from union?
Nov 7 '06 #1
Share this Question
Share on Google+
4 Replies


Expert 100+
P: 1,510
how a structure is different from union?
A union is similar to a structure in the way that it is declared and how its members are accessed, but there is a fundamental difference in the way storage is allocated:

structures: each member has its own area of storage
unions: the members use the same area of storage, i.e. they overlay each other.
Nov 7 '06 #2

100+
P: 111
At a time u can store only one value in union. Because, all variables occupy the same memory. If u store 2 values it will affect the other variable.
Nov 15 '06 #3

P: 23
consider the code below,

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. union koder {
  3.  
  4.                   char c;
  5.                   int i;
  6.                   double d;
  7.               };
  8.  
  9. main()
  10.  {
  11.    union  koder  new;
  12.    printf("\n %d",sizeof(new));
  13. }
#
Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h
  2. union koder {
  3.  
  4.                   char c;
  5.                   int i;
  6.                   double d;
  7.               };
  8. main()
  9.  {
  10.     union  koder  new;
  11.    printf("\n %d",sizeof(new));
  12.  
  13. }
  14.  
first code peice shows a union,when u print the size of the union it will give u the size of the largest member present in union .so at a time only any one member of the union can be accessed
But in second case the size of the structure gives u ,the 16 bytes(with gcc obvious) This includes the padding considerations,so equall to sum of sizes of all the element present.Thus we can understand that in a structure we can all elements or a single element.
Nov 15 '06 #4

P: 23
i mean we can access single element or all elements at a given time
Thanks
Nov 15 '06 #5

Post your reply

Sign in to post your reply or Sign up for a free account.