Unit 2 Structure Notes APC
Unit 2 Structure Notes APC
The structure in C is a user-defined data type that can be used to group items of
possibly different types into a single type. The struct keyword is used to define the
structure in the C programming language. The items in the structure are called
its member and they can be of any valid data type.
Structures (also called structs) are a way to group several related variables into one
place. Each variable in the structure is known as a member of the structure. Unlike
an array, a structure can contain many different data types (int, float, char, etc.).
struct Student{
int roll_no;
char name[30];
};
Here, the struct is a keyword, Student is a tag name, roll_no and name are its
members.
Using the struct keyword, we can create a workspace for any heterogeneous
and homogeneous type of data to store and manipulate at a single place.
#include <stdio.h>
int main()
{
APC NOTES_UNIT_II_Structure Rakesh Pandit
// Declaring two Student type variables
Student s1, s2;
return 0;
}
Output:
1 shubh
2 pachori
But if we want to input values by the keyboard then we have to use a different
method for it.
#include <stdio.h>
int main()
{
struct Student {
// name and roll_no are its member
char name[20];
int rollno;
} Student;
return 0;
}
Output:
101 Subh
102 Pranit
#include <stdio.h>
/*structure declaration*/
struct employee{
char name[30];
int empId;
float salary;
};
int main()
{
/*declare structure variable*/
struct employee emp;
Output
Enter details :
Name ?:Mike
ID ?:1120
Salary ?:76543
return 0;
}
OUTPUT:
size of structure in bytes : 16
Address of id1 = 675376768
Address of id2 = 675376772
Address of a = 675376776
Both structure variables and in-built data type gets same treatment in C
programming language. C language allows us to create an array of
structure variable like we create array of integers or floating point value.
The syntax of declaring an array of structure, accessing individual array
elements and array indexing is same as any in-built data type array.
employees[5].age
#include <stdio.h>
int main(){
struct employee employees[10];
int counter, index, count, totalSalary;
return 0;
}
Output
struct student
{
char name[20];
int roll;
float marks[5]; /* This is array within structure
*/
};
struct student s;
#include<stdio.h>
struct student
{
char name[20];
int roll;
float marks[5]; /* This is array within structure
*/
};
int main()
{
struct student s;
int i;
float sum=0, p;
for(i=0;i< 5;i++)
{
APC NOTES_UNIT_II_Structure Rakesh Pandit
printf("Enter marks:\n");
scanf("%f",&s.marks[i]);
sum = sum + s.marks[i];
}
p = sum/5;
printf(“Student records and percentage is:\n”);
printf("Name : %s\n", s.name);
printf("Roll Number : %d\n", s.roll);
printf("Percentage obtained is: %f", p);
return 0;
}
Output
struct Employee
{
char name[50];
int age;
float salary;
}employee_one;
struct Employee *employee_ptr;
employee_ptr->salary;
struct employee {
char name[100];
int main(){
struct employee employee_one, *ptr;
return 0;
}
Output
Employee Details
Name : Jack
Age : 30
Salary = 1234.500000
Dept : Sales
// Driver code
int main()
{
int n = 3;
// Array of structure objects
struct employee emp[n];
// Details of employee 1
emp[0].ename = "Chirag";
emp[0].age = 24;
emp[0].phn_no = 1234567788;
emp[0].salary = 20000;
// Details of employee 2
emp[1].ename = "Arnav";
emp[1].age = 31;
emp[1].phn_no = 1234567891;
emp[1].salary = 56000;
// Details of employee 3
emp[2].ename = "Shivam";
emp[2].age = 45;
emp[2].phn_no = 1100661111;
emp[2].salary = 30500;
display(emp, n);
return 0;
}
Output
Name Age Phone Number Salary
Chirag 24 1234567788 20000
struct car {
char name[30];
int price;
};
int main()
{
struct car c = { "Tata", 1021 };
print_car_info(c);
return 0;
}
Output
Name : Tata
Price : 1021
Example 2: Using Call By Reference Method
• C
// C program to pass structure as an argument to the
// functions using Call By Reference Method
#include <stdio.h>
struct student {
char name[50];
int roll;
float marks;
};
display(&st1);
return 0;
}
Output
Name: Aman
Roll: 19
Marks: 8.500000
struct student {
char name[20];
int age;
float marks;
};
return s;
}
int main()
{
// structure variable s1 which has been assigned the
// returned value of get_student_data
struct student s1 = get_student_data();
// displaying the information
printf("Name: %s\n", s1.name);
return 0;
}
Output:
Enter name: Krishna
Enter age: 21
Enter marks: 99
Name: Krishna
Age: 21
Marks: 99.0
After defining the structure pointer, we need to initialize it, as the code is shown:
1. ptr = &structure_variable;
We can also initialize a Structure Pointer directly during the declaration of a pointer.
Pointer.c
#include <stdio.h>
int main()
{
struct Subject sub; // declare the Subject variable
struct Subject *ptr; // create a pointer variable (*ptr)
ptr = ⊂ /* ptr variable pointing to the address of the structure variable sub */
return 0;
Output:
To access the elements inside the structure we should be using the following
syntax
Above we have created two objects for the struct tagname. Those two objects
have independent memory allocated for each of them. Both of them can be
compared with the normal declaration of the variables for example:
int a;
int *a;
Structures play very important role in big systems where we need to combine
several data's into a set and need to capture multiples of that set, perform
operations and many more.
A small piece of code will help understand the use of structures better.
#include <stdio.h>
struct tagname {
char Char;
int Int;
float Dec;
};
StructObj.Char='H';
ptrStructObj->Int=927;
ptrStructObj->Dec=911.0f;
printf("%C\n",StructObj.Char);
printf("%d\n",ptrStructObj->Int);
printf("%f",ptrStructObj->Dec);
printf("\n");
return 0;
}
Output
H
927
911.000000
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
Output
Delhi
110001
1234567890
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
1. By separate structure
2. By Embedded structure
1) Separate structure
Here, we create two structures, but the dependent structure should be used inside the
main structure as a member. Consider the following example.
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
2) Embedded structure
The embedded structure enables us to declare the structure inside the structure.
Hence, it requires less line of codes but it can not be used in multiple data structures.
Consider the following example.
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
1. e1.doj.dd
2. e1.doj.mm
3. e1.doj.yyyy
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
APC NOTES_UNIT_II_Structure Rakesh Pandit
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
Union in C
Union can be defined as a user-defined data type which is a collection of different
variables of different data types in the same memory location. The union can also be
defined as many members, but only one member can contain a value at a particular
point in time.
Union is a user-defined data type, but unlike structures, they share the same memory
location.
struct abc
{
int a;
char b;
}
The above code is the user-defined structure that consists of two members, i.e., 'a' of
type int and 'b' of type character. When we check the addresses of 'a' and 'b', we
found that their addresses are different. Therefore, we conclude that the members in
the structure do not share the same memory location.
When we define the union, then we found that union is defined in the same way as the
structure is defined but the difference is that union keyword is used for defining the
APC NOTES_UNIT_II_Structure Rakesh Pandit
union data type, whereas the struct keyword is used for defining the structure. The
union contains the data members, i.e., 'a' and 'b', when we check the addresses of both
the variables then we found that both have the same addresses. It means that the
union members share the same memory location.
The below figure shows the pictorial representation of the structure. The structure has
two members; i.e., one is of integer type, and the another one is of character type.
Since 1 block is equal to 1 byte; therefore, 'a' variable will be allocated 4 blocks of
memory while 'b' variable will be allocated 1 block of memory.
The below figure shows the pictorial representation of union members. Both the
variables are sharing the same memory location and having the same initial address.
In union, members will share the memory location. If we try to make changes in any of
the member then it will be reflected to the other member as well. Let's understand this
concept through an example.
1. union abc
2. {
3. int a;
4. char b;
5. }var;
6. int main()
7. {
8. var.a = 66;
9. printf("\n a = %d", var.a);
10. printf("\n b = %d", var.b);
11. }
In the above code, union has two members, i.e., 'a' and 'b'. The 'var' is a variable of
union abc type. In the main() method, we assign the 66 to 'a' variable, so var.a will
print 66 on the screen. Since both 'a' and 'b' share the memory location, var.b will print
'B' (ascii code of 66).
union abc{
int a;
char b;
float c;
As we know, the size of int is 4 bytes, size of char is 1 byte, size of float is 4 bytes, and
the size of double is 8 bytes. Since the double variable occupies the largest memory
among all the four variables, so total 8 bytes will be allocated in the memory. Therefore,
the output of the above program would be 8 bytes.
#include <stdio.h>
union abc
{
int a;
char b;
};
int main()
{
union abc *ptr; // pointer variable declaration
union abc var;
var.a= 90;
ptr = &var;
printf("The value of a is : %d", ptr->a);
return 0;
}
In the above code, we have created a pointer variable, i.e., *ptr, that stores the address
of var variable. Now, ptr can access the variable 'a' by using the (->) operator. Hence
the output of the above code would be 90.
o Books
o Shirts
struct store
{
double price;
char *title;
char *author;
int number_pages;
int color;
int size;
char *design;
};
The above structure consists of all the items that store owner wants to store. The above
structure is completely usable but the price is common property in both the items and
the rest of the items are individual. The properties like price, *title, *author, and
number_pages belong to Books while color, size, *design belongs to Shirt.
int main()
{
struct store book;
book.title = "C programming";
book.author = "Paulo Cohelo";
book.number_pages = 190;
book.price = 205;
printf("Size is : %ld bytes", sizeof(book));
return 0;
}
In the above code, we have created a variable of type store. We have assigned the
values to the variables, title, author, number_pages, price but the book variable does
not possess the properties such as size, color, and design. Hence, it's a wastage of
memory. The size of the above structure would be 44 bytes.
Suppose that you want to store the data of employee in your C/C++ project, where
you have to store the following different parameters:
o Id
o Name
o Department
o Email Address
One way to store 4 different data by creating 4 different arrays for each parameter,
such as id[], name[], department[], and email[]. Using array id[i] represents the id of the
ith employee. Similarly, name[i] represents the name of ith employee (name). Array
element department[i] and email[i] represent the ith employee's department and email
address.
The advantage of using a separate array for each parameter is simple if there are only
a few parameters. The disadvantage of such logic is that it is quite difficult to manage
employee data. Think about a scenario in which you have to deal with 100 or even
more parameters associated with one employee. It isn't easy to manage 100 or even
more arrays. In such a condition, a struct comes in.
Example
struct employee
{
int id;
char name[50];
string department;
string email;
};
What is a Union?
In "c," programming union is a user-defined data type that is used to store the
different data type's values. However, in the union, one member will occupy the
memory at once. In other words, we can say that the size of the union is equal to the
size of its largest data member size. Union offers an effective way to use the same
memory location several times by each data member. The union keyword is used to
define and create a union data type.
Syntax of Union
union [union name]
{
type member_1;
type member_2;
...
type member_n;
};
Example
union employee
{
string name;
string department;
int phone;
string email;
};
APC NOTES_UNIT_II_Structure Rakesh Pandit
Example of Structure and Union showing the
difference in C
Let's see an example of structure (struct) and union in c programming, illustrating the
various differences between them.
printf("data of structure:\n integer: %d\n decimal: %.2f\n name: %s\n", stru.integer, str
u.decimal, stru.name);
printf("\ndata of union:\n integer: %d\n" "decimal: %.2f\n name: %s\n", uni.inte
ger, uni.decimal, uni.name);
// difference five
printf("\nAccessing all members at a time:");
stru.integer = 163;
stru.decimal = 75;
strcpy(stru.name, "John");
printf("\ndata of structure:\n integer: %d\n " "decimal: %f\n name: %s\n", stru.integer,
stru.decimal, stru.name);
uni.integer = 163;
uni.decimal = 75;
strcpy(uni.name, "John");
printf("\ndata of union:");
uni.integer = 140;
uni.decimal = 150;
strcpy(uni.name, "Mike");
//difference four
printf("\nAltering a member value:\n");
stru.integer = 512;
printf("data of structure:\n integer: %d\n decimal: %.2f\n name: %s\n", stru.inte
ger, stru.decimal, stru.name);
uni.integer = 512;
printf("data of union:\n integer: %d\n decimal: %.2f\n name: %s\n", uni.integer,
uni.decimal, uni.name);
Output
data of structure:
integer: 5
decimal: 15.00
name: John
data of union:
integer: 5
decimal: 0.00
name:
sizeof structure: 28
sizeof union: 20
Struct Union
The struct keyword is used to define a structure. The union keyword is used to define union.
When the variables are declared in a structure, When the variable is declared in the union, the
the compiler allocates memory to each variables compiler allocates memory to the largest size variable
member. The size of a structure is equal or member. The size of a union is equal to the size of its
greater to the sum of the sizes of each data largest data member size.
member.
Each variable member occupied a unique Variables members share the memory space of the
memory space. largest size variable.
Changing the value of a member will not affect Changing the value of one member will also affect
other variables members. other variables members.
Each variable member will be assessed at a time. Only one variable member will be assessed at a time.
We can initialize multiple variables of a structure In union, only the first data member can be initialized.
at a time.
The structure allows initializing multiple variable Union allows initializing only one variable member at
members at once. once.
It is used to store different data type values. It is used for storing one at a time from different data
type values.
It allows accessing and retrieving any data It allows accessing and retrieving any one data
member at a time. member at a time.
In the above declaration, we define the enum named as flag containing 'N' integer
constants. The default value of integer_const1 is 0, integer_const2 is 1, and so on. We
can also change the default value of the integer constants at the time of the
declaration.
For example:
enum fruits{
mango=2,
apple=1,
strawberry=5,
papaya=7,
};
enum status{false,true};
In the above statement, we have declared the 's' variable of type status.
enum status{false,true} s;
In this case, the default value of false will be equal to 0, and the value of true will be
equal to 1.
#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
enum weekdays w; // variable declaration of weekdays type
w=Monday; // assigning value of Monday to w.
printf("The value of w is %d",w);
return 0;
}
In the above code, we create an enum type named as weekdays, and it contains the
name of all the seven days. We have assigned 1 value to the Sunday, and all other
names will be given a value as the previous value plus one.
Output
#include <stdio.h>
enum months{jan=1, feb, march, april, may, june, july, august, september, october, nove
mber, december};
int main()
{
// printing the values of months
for(int i=jan;i<=december;i++)
{
printf("%d, ",i);
}
return 0;
}
In the above code, we have created a type of enum named as months which consists
of all the names of months. We have assigned a '1' value, and all the other months will
be given a value as the previous one plus one. Inside the main() method, we have
defined a for loop in which we initialize the 'i' variable by jan, and this loop will iterate
till December.
Output
#include <stdio.h>
enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum days d;
d=monday;
switch(d)
{
case sunday:
printf("Today is sunday");
break;
case monday:
printf("Today is monday");
break;
case tuesday:
printf("Today is tuesday");
break;
case wednesday:
printf("Today is wednesday");
break;
case thursday:
printf("Today is thursday");
break;
case friday:
printf("Today is friday");
break;
case saturday:
printf("Today is saturday");
break;
}
return 0;
}
Output
o The enum names available in an enum type can have the same value. Let's look at the
example.
#include <stdio.h>
int main(void) {
enum fruits{mango = 1, strawberry=0, apple=1};
printf("The value of mango is %d", mango);
printf("\nThe value of apple is %d", apple);
return 0;
}
Output
o If we do not provide any value to the enum names, then the compiler will automatically
assign the default values to the enum names starting from 0.
o We can also provide the values to the enum name in any order, and the unassigned
names will get the default value as the previous one plus one.
o The values assigned to the enum names must be integral constant, i.e., it should not
be of other types such string, float, etc.
o All the enum names must be unique in their scope, i.e., if we define two enum having
same scope, then these two enums should have different enum names otherwise
compiler will throw an error.
#include <stdio.h>
APC NOTES_UNIT_II_Structure Rakesh Pandit
enum status{success, fail};
enum boolen{fail,pass};
int main(void) {
Output
o In enumeration, we can define an enumerated data type without the name also.
#include <stdio.h>
enum {success, fail} status;
int main(void) {
status=success;
printf("The value of status is %d", status);
return 0;
}
Output