Professional Documents
Culture Documents
User Defined Datatypes (UDT)
User Defined Datatypes (UDT)
1. Structures
● Structure is a collection of the same or different data type under one common
name.
● Syntax:
○ struct structure_name
{
///structure members
};
● To create structure variable
○ struct structure_name variable_name;
● Example:
struct Student
{
int id;
char name[20];
char address[30];
};
Structure copy
● In the case of arrays we learned that copying one array to another is not
straight forward, we need to use a loop.
● But in the case of structure, it can be copied by using assignment operator
● Example:
○ struct Student s1 = {10,"Rama","Bangalore"};
s2 = s1;
Structure Pointers
● We can have structure pointer to store the address of structure variable
● For example:
● As you can see in the above example structure takes uipto 184 bytes in stack
which is huge in size, so normally pass by value method is avoided in case of
structure
● As you can see in pass by reference it only need 4/8 bytes of memory.
Returning structure from function
● Like a normal variable a structure can be returned from function if its created
in the heap like below:
Array of structure
● Array of structure is a collection of more than 2 structure variables
● For example,
○ struct Student
{
int id;
char name[20];
char address[60];
};
struct Student s[5];
Nested Structures
Structure Padding
struct Student
char ch1;
int id;
char ch2;
2. Unions
● Like structures, union is also a user defined datatype which can have the
same or different types of data.
● Major difference between structure and union is, union shares the memory of
the largest member among the other members.
● E.g.,
○ union Test
{
char option;
Int id;
double height;
};
● In above example height is biggest member of the union so, the sizeof the
union will be 8bytes and that memory is shared among the others
3. Typedefs
● Typedefinition is used to create a new name to the xisting datatype
● E.g,
○ typedef unsigned long int uli;
4. Enum
● Enum is a another user defined datatype which is used to group named
constant under a single name.
● It is called as set of named integral values.
● For example:
○ enum boolean
{
false,
true
}
● In the enums first named constant always will have 0 as initialised value and
next member will be incremented by 1.
● So, false is having value 0 and true is having value 1.
● We can also initialised own integral vlaues to the enum members like,
○ enum boolean
{
green = 90,
Blue = 40
}