Definition
|
A structure is a collection of variables under a single name. These variables can be of different types, and each has a name which is used to select it from the structure.
|
A union is a special data type that enables to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time
|
Memory Allocation
|
In a structure, all of its data members are stored in contiguous memory locations. The size of an object of a struct is, therefore, the size of the sum of all its data members.
Example for Structure: struct tech { char p; int x; float Q;
int y; }D; memory allocated for D will be 1+2+4+2= 9 bytes
|
A union is a class all of whose data members are mapped to the same address within its object. The size of an object of a union is, therefore, the size of its largest data member.
Example for union :
union tech { char p; int x; float q; }N; the memory allocated for union will be 4 bytes (that is largest size among members)
|
No comments:
Post a Comment