What is structure?
• Structure is a user-defined data type in C which allows you tocombine different data types to store a particular type of record.
• Structure helps to construct a complex data type in moremeaningful way. It is somewhat similar to an Array.
• The only difference is that array is used to store collection ofsimilar datatypes while structure can store collection of any type ofdata.
• Structure is used to represent a record.
• Suppose you want to store record of Student which consists ofstudent name, address, roll number and age. You can define astructure to hold this information.
2
Structure Definition
• Keyword struct is used for creating a structure.
• Syntax of structure :
• We can create the structure for a person as mentioned :
3
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};
struct person
{
char name[50];
int no;
float salary;
};
Structure Variable Declaration
• When a structure is defined, it creates a user-defined type but, no
storage or memory is allocated.
• For the structure of a person, variable can be declared as:
struct person
{
char name[50];
int citNo;
float salary;
};
int main()
{
struct person person1, person2;
return 0;
}
4
Structure Variable Declaration
• Another way of creating a structure variable is:
struct person
{
char name[50];
int citNo;
float salary;
} person1, person2;
• In both cases, two variables person1, person2 of type struct person
are created.
5
Accessing members of a structure
• Members of structures i.e. variables declared in a structure can be
assessed using period or member assess operator(.)
• Any member of a structure can be accessed as:
structure_variable_name.member_name
• Suppose, we want to access salary for variable person2. Then, it can
be accessed as:
person2.salary
6
Using typedef while using structure• Writing struct structure_name variable_name; to declare a structure
variable isn't intuitive as to what it signifies, and takes some considerable
amount of development time.
• So, use typedef to name the structure as a whole. For example:
typedef struct complex
{
int imag;
float real;
} comp;
int main()
{
comp comp1, comp2;
}
• Here, typedef keyword is used in creating a type comp (which is of type
as struct complex).
• Then, two structure variables comp1 and comp2 are created by this
comp type.7
Structure initialization• Like any other data type, structure variable can also be initialized at
compile time.
struct Person
{
float height;
int weight;
int age;
};
struct Person p1 = { 180.75 , 73, 23 }; //initialization
or
struct Person p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
• You can copy an entire structure to another structure by just equating.
i.e. p2 = p1, this will copy all the values in p1 to p2.8
Structure initializationOne more way of initializing can be :
struct Person
{
float height;
int weight;
int age;
} p1 = { 180.75 , 73, 23 };
struct student
{
int mark1;
int mark2;
int mark3;
} sub1={67};
Though, there are three members of structure, only one is initialized ,
Then remaining two members are initialized with Zero (default value).
int will take 0, float/double will take 0.000000 and char will take NULL.9
Array of structures• Structure is used to store the information of One particular object but if
we need to store such 100 objects then Array of Structure is used.
struct Bookinfo
{
char bname[20];
int pages;
int price;
}Book[100];
• Here Book structure is used to Store the information of one Book.
• In case, if we need to store the Information of 100 books then Array ofStructure is used.
• b1[0] stores the Information of 1st Book , b1[1] stores the informationof 2nd Book and so on. We can store the information of 100 books.
10
Nested Structures• Structure written inside another structure is called as nesting of two
structures.
• We can write one Structure inside another structure as member of another
structure.
• WAY 1 : Declare two separate structures
• Structure members are accessed using dot operator.
• ‘date‘ structure is nested within Employee Structure.
• Members of the ‘date‘ can be accessed using ’employee’
• emp1 & doj are two structure names (Variables)
• Accessing Month Field : emp1.doj.month
• Accessing day Field : emp1.doj.day
• Accessing year Field : emp1.doj.year
11
struct date
{
int date;
int month;
int year;
};
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
} emp1;
Nested Structures• WAY 2 : Declare embedded structures
• Structure members are accessed using dot operator.
• ‘date‘ structure is nested within Employee Structure.
• Members of the ‘date‘ can be accessed using ’employee’
• emp1 & doj are two structure names (Variables)
• Accessing Month Field : emp1.doj.month
• Accessing day Field : emp1.doj.day
• Accessing year Field : emp1.doj.year
12
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp1;
Size of Structure• Different ways of calculating size of structure
• By observation
• By using sizeof() Operator
• WAY 1 : Calculate by adding Individual Sizes
• Size = size of 'Pages' + size of 'Name' + size of 'Author' + size of 'Price'
= 4 + 10 * 1 + 10 * 1 + 4
= 4 + 10 + 10 + 4
= 28
13
struct Book
{
int pages;
char name[10];
char author[10];
float price;
}b1;
Passing structure to function
• There are mainly two ways to pass structures to a function:• Passing by value
• Passing by reference
15
Passing structure by value
• A structure variable can be passed to the function as an argument asa normal variable.
• If structure is passed by value, changes made to the structurevariable inside the function definition does not reflect in theoriginally passed structure variable.
• Function prototype should be below to the structure declarationotherwise compiler shows error.
16
Passing structure by reference
• The memory address of a structure variable is passed to functionwhile passing it by reference.
• If structure is passed by reference, changes made to the structurevariable inside function definition reflects in the originally passedstructure variable.
• Use the same concept of passing an address and receiving it inpointer variable in the called function.
18
Passing structure by reference
• In this program, structure variables dist1 and dist2 are passed byvalue to the add function (because value of dist1 and dist2 does notneed to be displayed in main function).
• But, dist3 is passed by reference ,i.e, address of dist3 (&dist3) ispassed as an argument.
• Due to this, the structure pointer variable d3 inside the add functionpoints to the address of dist3 from the calling main function. So,any change made to the d3 variable is seen in dist3 variable in mainfunction.
• As a result, the correct sum is displayed in the output.
20
Structure and Pointer
• Structures can be created and accessed using pointers. A pointer
variable of a structure can be created as below:
struct name {
member1;
member2;
.
.
};
int main()
{
struct name *ptr;
}
• Here, the pointer variable of type struct name is created.
21
Accessing structure's member through pointer
• Can be accessed by referencing pointer to another address to access
memory.
• Using -> operator (Membership Operator) to access structure
pointer member
• Structure pointer member can also be accessed using -> operator.
• (*personPtr).age is same as personPtr->age
• (*personPtr).weight is same as personPtr->weight
22
Pointer to array of structures
24
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;
struct Book b[10]; //Array of structure variables
struct Book* p; //Pointer of Structure type
p = &b;
}
Pointer to array of structures
25
struct Cricket
{
char team1[20];
char team2[20];
char ground[18];
int result;
}match[4] = {
{"IND","AUS","PUNE",1},
{"IND","PAK","NAGPUR",1},
{"IND","NZ","MUMBAI",0},
{"IND","SA","DELHI",1}
};
int main()
{
struct Cricket *ptr = match;
return 0;
}
Function returning structure
27
• Refer the following programs:• returning_structure.c
• returning_array of structures.c
Pointer to structure within the same structure : Self Referential
• In this Type , Structure has pointer to itself.
• Pointer stores the address of the Structure of same type.
• Syntax :
struct node
{
int data;
struct node *ptr; //Pointer to Struct node
};
28
Pointer to structure within the same structure : Self Referential
29
• Here ptr stores address of Structure node.
• This is useful in Dynamic Memory Allocation and Creating Linked Lists.
Union
30
• Unions are quite similar to structures in C. Like structures, unions are also derived data types.
• Defining a union is as easy as replacing the keyword struct with the keyword union.
• Again, the member of unions can be accessed in similar manner as structures.
Size allocation in Union
31
• More memory is allocated to structures than union.
• There is a difference in memory allocation between union andstructure.
• The amount of memory required to store a structure variable is thesum of memory size of all members.
• But, the memory required to store a union variable is the memoryrequired for the largest element of an union.
Why difference in size allocation in Union?
32
• Only one union member can be accessed at a time.
• In the case of structure, all of its members can be accessed at anytime.
• But, in the case of union, only one of its members can be accessedat a time and all other members will contain garbage values.
Why difference in size allocation in Union?
34
• Initially in the program, Hillary is stored in job1.name and all othermembers of job1, i.e. salary, workerNo, will contain garbage values.
• But, when user enters the value of salary, 1234.23 will be stored injob1.salary and other members, i.e. name, workerNo, will nowcontain garbage values.
• Thus in the output, salary is printed accurately but, name displayssome random string.
• Record1 union variable:
• “Raju” is assigned to union member “record1.name” . The memory location name is“record1.name” and the value stored in this location is “Raju”.
• Then, “Maths” is assigned to union member “record1.subject”. Now, memory location name ischanged to “record1.subject” with the value “Maths” (Union can hold only one member at a time).
• Then, “86.50” is assigned to union member “record1.percentage”. Now, memory location nameis changed to “record1.percentage” with value “86.50”.
• Like this, name and value of union member is replaced every time on the common storage space.
• So, we can always access only one union member for which value is assigned at last. We can’taccess other member values.
• So, only “record1.percentage” value is displayed in output. “record1.name” and“record1.percentage” are empty.
• Record2 union variable:
• If we want to access all member values using union, we have to access the member beforeassigning values to other members as shown in record2 union variable in this program.
• Each union members are accessed in record2 example immediately after assigning values tothem.
• If we don’t access them before assigning values to other member, member name and value will beover written by other member as all members are using same memory.
• We can’t access all members in union at same time but structure can do that.
36
37
C Structure C Union
Structure allocates storage space for all its
members separately.
Union allocates one common storage space
for all its members.
Union finds that which of its member needs
high storage space over other members and
allocates that much space
Structure occupies higher memory space.Union occupies lower memory space over
structure.
We can access all members of structure at a
time.
We can access only one member of union at a
time.
Structure example:
struct student
{
int mark;
char name[6];
double average;
};
Union example:
union student
{
int mark;
char name[6];
double average;
};
For above structure, memory allocation will
be like below.
int mark – 2B (considering 2 bytes)
char name[6] – 6B
double average – 8B
Total memory allocation = 2+6+8 = 16 Bytes
For above union, only 8 bytes of memory will
be allocated since double data type will occupy
maximum space of memory over other data
types.
Total memory allocation = 8 Bytes