Structure and union
Structure and union
};
General format of Structure
struct tag_name
{
data type member1;
data type member2;
data type member2;
------------ ------------
};
Declaring structure variables
struct Point
A valid initialization.
{
Member x gets value 0
int x, y;
and y gets value 1.
};
The order of declaration
int main()
is followed.
{
struct Point p1 = {0, 1};
}
Type defined structures
• We can also use keyword typedef to define a structure as follows:
typedef struct
{
type member1;
type member2;
}
Variables defining methods:
#include<stdio.h> #include<stdio.h>
struct Point{
typedef struct Point{
int x; int x;
int y;
}; int y;
} Point;
int main() {
struct Point p1; int main()
{
p1.x = 1;
Point p1;
p1.y = 3; p1.x = 1;
printf("%d \n", p1.x); p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
printf("%d \n", p1.y);
return 0; return 0;
} }
Accessing Structure Members
• The members themselves are not
#include<stdio.h>
variables.
struct Point{
• They should be linked to the
int x;
structure variables in order to make
int y;
them meaningful members.
};
• The link between a member and a
int main() {
variable is established using the
struct Point p1;
member operator ‘.’
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
}
Rules for Initializing for structures
• We cannot initialize individual members inside the structure
template.
• The order of values enclosed in braces must match the order of
members in the structure definition.
• It is permitted to have a partial initialization. We can initialize only
first few members and leave the remaining blank. The uninitialized
members should be only at the end of the list.
• The uninitialized members will be assigned default values as follows:
• Zero for integer and floating point numbers.
• ‘\0’ for characters and strings.
Copying and comparing structure variables
• Two variables of same structure type can be copied the same way as
ordinary variables.
• If p1 and p2 belong to the same structure, then p1=p2;
p2=p1; are valid
• Let’s create structure called student to store name, roll no and marks of 5 subjects.
struct student
{
char name[20];
int roll_no;
float marks[5];
}std1;
printf("Name\tRoll no\tAverage\n\n");
struct student
{
char name[20]; //1 Byte each = 20 Bytes
int roll_no; //4 Bytes Question:
float marks[2]; //4 Byte each = 8 Bytes How do we get the size of the
}; structure?
• C provides us the feature of nesting one structure within another structure by using which, complex
data types are created.
• For example, we may need to store the address of an entity employee in a structure. The attribute
address may also have the subparts as street number, city, state, and pin code. Hence, to store the
address of the employee, we need to store the address of the employee into a separate structure and
nest the structure address into the structure employee.
• The structure can be nested in the following ways.
• By Separate structure
• By Embedded structure
1. SEPARATE STRUCTURE
• We can access the member of the nested structure by… For Example:
Outer_structure.Nested_structure.Member
emp1.doj.dd;
emp1.doj.mm;
emp1.doj.yyyy;
Pointers to Structure
• A structure pointer is defined as the pointer which points to the
address of the memory block that stores a structure known as the
structure pointer.
• Complex data structures like Linked lists, trees, graphs, etc. are
created with the help of structure pointers.
• The structure pointer tells the address of a structure in memory by
pointing the variable to the structure variable.
Accessing the Structure Member with the Help of Pointers
• There are two ways to access the members of the structure with the
help of a structure pointer:
• With the help of (*) asterisk or indirection operator and (.) dot
operator.
• With the help of ( -> ) Arrow operator.
// C Program to demonstrate Structure pointer
#include <stdio.h> s1.batch = 2023;
#include <string.h>
printf("Roll Number: %d\n", (*ptr).roll_no);
struct Student {
int roll_no; printf("Name: %s\n", (*ptr).name);
char name[30];
char branch[40]; printf("Branch: %s\n", (*ptr).branch);
int batch;
}; printf("Batch: %d", (*ptr).batch);
int main() return 0;
{ }
struct Student s1;
struct Student* ptr = &s1;
s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
// C Program to demonstrate Structure pointer ptr = &s;
// Taking inputs
printf("Enter the Roll Number of Student\n");
#include <stdio.h> scanf("%d", &ptr->roll_no);
#include <string.h> printf("Enter Name of Student\n");
scanf("%s", &ptr->name);
// Creating Structure Student printf("Enter Branch of Student\n");
struct Student { scanf("%s", &ptr->branch);
int roll_no; printf("Enter batch of Student\n");
char name[30]; scanf("%d", &ptr->batch);
char branch[40];
int batch; // Displaying details of the student
}; printf("\nStudent details are: \n");
printf("Roll No: %d\n", ptr->roll_no);
// variable of structure with pointer defined printf("Name: %s\n", ptr->name);
printf("Branch: %s\n", ptr->branch);
struct Student s, *ptr; printf("Batch: %d\n", ptr->batch);
• A structure can be passed to any function from main function or from any sub function.
• If structure is defined within the function only then it won’t be available to other functions unless
it is passed to those functions by value or by address.
• Else, we have to declare structure variable as global variable. That means, structure variable
should be declared outside the main function. So, this structure will be visible to all the functions
in a C program.
• It can be done in below ways.
EXAMPLE
#include <stdio.h> record.id=1;
#include <string.h> strcpy(record.name, "Raju");
record.percentage = 86.5;
struct student
{ func(record);
int id; return 0;
char name[20]; }
float percentage;
}; void func(struct student record)
{
void func(struct student record); printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
int main() printf(" Percentage is: %f \n", record.percentage);
{ }
struct student record;
EXAMPLE
#include <stdio.h> record.id=1;
#include <string.h> strcpy(record.name, "Raju");
record.percentage = 86.5;
struct student
{ func(&record);
int id; return 0;
char name[20]; }
float percentage;
}; void func(struct student *record)
{
void func(struct student *record); printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
int main() printf(" Percentage is: %f \n", record->percentage);
{ }
struct student record;
UNION
• A union is a special data type available in C that allows storing 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.
• Unions provide an efficient way of using the same memory location for multiple
purposes.
• Defining a Union: To define a union, you must use the union statement in the
same way as you did while defining a structure. The union statement defines a
new data type with more than one member for your program.
UNION
SYNTAX
union keyword
union union_name
{
//Members / Fields of Union
}union_var; semicolon
STRUCTURE VS UNION IN C
structure union
Keyword “struct” is used to define the structure. “union” is used to define union.
Size When a variable is associated with the When a variable is associated with the union,
structure, compiler allocates memory for each compiler allocates memory by considering
member. the size of the largest member.
The size of structure is greater than or equal The size of union is the size of the largest
to the sum of the sizes of it’s members. member.
Memory Each member is assigned a unique storage Memory allocated is shared by individual
location. members.
Value altering Altering value of a member will not affect Altering value of a member will affect value
other members. of other members.
Accessing Individual members can be accessed at a Only one member can be accessed at a time.
members time.
Initialization Many members of a structure can be Only the first member of a union can be
of members initialized at a time. initialized.
Example of Restrictions
#include<stdio.h>
union Address
{
char name[50];
char street[100];
};
int main()
{
union Address std = {"dipsi", "75th Street"};
printf("\nname: %s",std.name);
printf("\nstreet: %s",std.street);
printf("\n");
return 0;
}
SIMILARITIES BETWEEN STRUCTURE
AND UNION
• Both are user-defined data types used to store data of different types as a single unit.
• A structure or a union can be passed by value to functions and returned by value by functions.
The argument must have the same type as the function parameter.
• ‘.’Operator is used for accessing members.
SIZE OF UNION
#include<stdio.h>
union student
{
char name[20]; //1 Byte each = 20 Bytes
int roll_no; //4 Bytes Question:
float marks[2]; //4 Byte each = 8 Bytes How do we get the size of the union?
};
Answer:
int main() • By size of the largest member.
{
union student std[2];