Full width home advertisement

Post Page Advertisement [Top]

What is union and struct in C Language? What is the difference between union and struct?

What is struct?

struct is an user-defined data type which stores heterogeneous types of data. struct is a combination of primitive (predefined) data types which are called as member of struct. These member can be access by using  struct variable with period "." following by the member name.

Syntax:
//Creating a struct data type
struct mtype{
  int id;
  char name[20];
}

//making a variable of "mtype" which is created above.
struct mtype myDataType;

//using new variable, storing or retrieving value.
myDataType.id = 15;
myDataType.name = "Masoom";
printf("%d",myDataType.id);
printf("%s",myDataType.name);

Simple program of struct in C

#include <stdio.h>

struct mystruct {
int roll;
char name[50];
int age;
}
int main(){
struct mystruct var1;

var1.name = "Masoom";
var1.age = 20;
var1.id = 9121;

printf("Name: %s",var1.name);
printf("Age: %d",var1.age);
printf("Id: %d",var1.id);

return 0;

}


What is union?

union is an user-defined data type and same as the struct. But it store different types of data in same memory location. Therefore the size of memory it reserve is the one of it member which size is high among any member. That's mean you can only assign value to any one member. If you assign the value to another member, previous member's value will overwrite.


Syntax:
//Creating a struct data type
union mtype{
  int uniqueId;
  char uniqueName;
}

//making a variable of "mtype" which is created above.
union mtype var1;

Example:

var1.uniqueId = 12;
var1.uniqueName = "hello"; 
//Here unique id is over  write by unique name.
//That's means you can use only one member of union at a time, if another member initialize, old member lose their value.

Difference between union and struct.

union use same memory for all members.
struct use seperate memory for all members.

In union, only one member can use at a time.
In struct, all member can use at same time.

union reverse memory location for one member whose size is large than anyone in union.
struct reverse memory location for all members.

No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib