Skip to main content

What are the differences between a union and a structure in C?

What are the differences between a union and a structure in C?
A union is a way of providing an alternate way of describing the same memory area. In this way, you could have a struct that contains a union, so that the “static”, or similar portion of the data is described first, and the portion that changes is described by the union. The idea of a union could be handled in a different way by having 2 different structs defined, and making a pointer to each kind of struct. The pointer to struct “a” could be assigned to the value of a buffer, and the pointer to struct “b” could be assigned to the same buffer, but now a->some field and b->some otherfield are both located in the same buffer. That is the idea behind a union. It gives different ways to break down the same buffer area.
The difference between structure and union are: 1. union allocates the memory equal to the maximum memory required by the member of the union but structure allocates the memory equal to the total memory required by the members. 2. In union, one block is used by all the member of the union but in case of structure, each member have their own memory space
Difference Between Stucture and Union :
Structure
Union
i. Access Members
We can access all the members of structure at anytime.
Only one member of union can be accessed at anytime.
ii. Memory Allocation
Memory is allocated for all variables.
Allocates memory for variable which variable require more memory.
iii. Initialization
All members of structure can be initialized
Only the first member of a union can be initialized.
iv. Keyword
‘struct’ keyword is used to declare structure.
‘union’ keyword is used to declare union.
v. Syntax
struct struct_name
{
    structure element 1;
    structure element 2;
        ----------
        ----------
    structure element n;
}struct_var_nm;
union union_name
{
    union element 1;
    union element 2;
        ----------
        ----------
    union element n;
}union_var_nm;
vi. Example
struct item_mst
{
    int rno;
    char nm[50];
}it;
union item_mst
{
    int rno;
    char nm[50];
}it;

Difference in their Usage:

While structure enables us treat a number of different variables stored at different in memory , a union enables us to treat the same space in memory as a number of different variables. That is a Union offers a way for a section of memory to be treated as a variable of one type on one occasion and as a different variable of a different type on another occasion.
There is frequent requirement while interacting with hardware to access access a byte or group of bytes simultaneously and sometimes each byte individually. Usually union is the answer.
=======Difference With example=======
Lets say a structure containing an int,char and float is created and a union containing int char float are declared.
struct TT{ int a; float b; char c; } Union UU{ int a; float b; char c; }
sizeof TT(struct) would be >9 bytes (compiler dependent-if int,float, char are taken as 4,4,1)
sizeof UU(Union) would be 4 bytes as supposed from above.If a variable in double exists in union then the size of union and struct would be 8 bytes and cumulative size of all variables in struct.

Detailed Example:

struct foo
{
char c;
long l;
char *p;
};
union bar
{
char c;
long l;
char *p;
};
A struct foo contains all of the elements c, l, and p. Each element is separate and distinct.
A union bar contains only one of the elements c, l, and p at any given time. Each element is stored in the same memory location (well, they all
start at the same memory location), and you can only refer to the element which was last stored. (ie: after “barptr->c = 2;” you cannot reference
any of the other elements, such as “barptr->p” without invoking undefined behavior.)
Try the following program. (Yes, I know it invokes the above-mentioned “undefined behavior”, but most likely will give some sort of output on most computers.)
==========
#include
struct foo
{
char c;
long l;
char *p;
};
union bar
{
char c;
long l;
char *p;
};
int main(int argc,char *argv[])
{
struct foo myfoo;
union bar mybar;
myfoo.c = 1;
myfoo.l = 2L;
myfoo.p = “This is myfoo”;
mybar.c = 1;
mybar.l = 2L;
mybar.p = “This is mybar”;
printf(“myfoo: %d %ld %s\n”,myfoo.c,myfoo.l,myfoo.p);
printf(“mybar: %d %ld %s\n”,mybar.c,mybar.l,mybar.p);
return 0;
}
==========
On my system, I get:
myfoo: 1 2 This is myfoo
mybar: 100 4197476 This is mybar
==========
credit to original author.
Structure: Structure is a combination elements, which can be predefined data types or other structure. The length/size of the structure is the sum of the length of its elements.
In C, structures cannot contain functions. in C++ it can.
Union: Union is a combination elements, which can be predefined data types or other union . But, the size/length of union is the maximum of internal elements.
the sizeof() operator returns the size slightly more than calculated size due to padding, which again depends on OS
== Answer == Union allocates the memory equal to the maximum memory required by the member of the union but structure allocates the memory equal to the total memory required by the members. In union,one block is used by all the member of the union but in case of structure, each member have their own memory space.

Comments

Popular posts from this blog

CAN INTERVIEW QUESTIONS

Qualifiers and Modifier in C

RTOS Real time operating system interview questions

CAN INTERVIEW QUESTIONS 2

What is UDS protocol

Memory mapping in c

TOP IOT PLATFORMS