Module 2 Structures
Module 2 Structures
Module2: Structures
• Defining a structure
• Structure initialization
• Array of structures
• Union
• Size of structure
• Definition
“A structure is a group of items in which each item can be of different datatype, and is known
as member of structure”. A structure is called record and member is called field.
• Defining a structure
o To define a structure, you must use the struct statement. The struct statement defines a new
data type, with more than one member.
o The format of the struct statement is as follows
struct structureName
{
dataType member1;
dataType member2;
---
dataType memberN;
};
• Example:
struct Student
{
int age;
char name[10];
float fees;
};
- Here struct Student declares a structure to hold the details of a student which consists of
3 data fields, namely age, name, and fees. These fields are called structure elements or
members.
- The above declaration does not allocate any memory. We must create variables to the
structure to allocate a memory for Structure student.
The declaration of structure does not allocate any memory. We must create variables to the
structure to allocate a memory for Structure student.
1. Declaring Structure variables separately
.struct Product
{ Creates two structure variables s1
char type; and s2, each of variables contain
two fields type and cost.
int cost;
} ;
struct Product s1, s2;
• Memory representation
s1 s2
type type
cost cost
Example:
include<string.h>
struct Student
{
char name[25];
int age;
};
void main()
{
struct Student s1; /* s1 is a variable of Student type */
s1.age = 18; /* accessing member age /*
strcpy(s1.name, "Viraaj"); /* accessing member name using function /*
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);
}
Example:
/* Write a program to accept rate and quantity of a product and display the total amount */
struct Product
{
float Price;
int Qty ;
};
main ( )
{
struct Product Pt ;
float total ;
printf (“Input the price of a product:”);
• Examplesscanfon(“%f”, &Pt.Price);
structure
printf (“Input the Total quantity purchased:”);
Write a program to create a structure named student which contains the fields as
scanf (“%d”, &Pt.Qty);
USN, name and phone. Read the details of one student from the user and display
Total = Pt.Price * Pt.Qty ;
the same.
printf (“Total Amount is: %f ”, Total);
}
Write a C program to store name, usn, test1, test2 and test3 marks. Read the
details of the student along with his Internal assessment marks of three tests.
Display the average of best two internals.
.struct Student {
int usn, test1, test2, test3;
char name[10];
} ;
void main()
{
. struct Student st;
int avg, top1, top2;
printf(“Enter USN of student: ”);
scanf(“%d”, &st.USN);
printf(“Enter Name of student: ”);
scanf(“%s”, st.name);
printf(“Enter Test1, Test2 and Test3 marks: ”);
scanf(“%d %d %d”, &st.test1, &st.test2, &st.test3);
Example:
void main()
{
struct car
{
char name[100];
float price;
};
struct car car1 ={"xyz", 987432.50};
printf("Name of car1 = %s\n",car1.name);
printf("Price of car1 = %f\n",car1.price);
• Two variables of the same structure type can be copied the same way as ordinary variables. If
persona1 and person2 belong to the same structure, then the following statements Are valid.
person1 = person2;
person2 = person1;
• C does not permit any logical operators on structure variables In case, we need to compare
them, we may do so by comparing members individually.
person1 = = person2
person1 ! = person2
C language doesn't permit any logical operations on structure variables.
• We can compare two structure variables but comparison of members of a structure can only be
done individually.
struct Student
{
int no;
char name [20];
float marks;
}
main ( )
{
int flag;
struct Student st1 = { 111, “Rao”, 72.50};
struct Student st2 = {222, “Reddy”, 67.80};
struct class stu3;
stu3 = stu2; // copying structure variables
flag = ( ( st3.no= = st2.no) && ( st3.marks = = st2.marks)) ? 1 : 0 ;
if ( flag==1)
{
printf (“ \n student 2 & student 3 are same \n”);
printf (“%d\t%s\t%f “ stu3.no, stu3.name, stu3.marks);
}
else
printf ( “\n student 2 and student 3 are different “);
}
• The only operation that can be applied to struct variables is assignment. Any other operation
(e.g. equality check, addition etc.) is not allowed on struct variables.
#include <stdio.h>
typedef struct complex {
float real;
float imag;
} complex;
int main() {
complex n1, n2, result;
Example: Accept Names and ages of a student and display the elder Students name.
struct Student
{
char name[20];
int age, index ;
};
main ( )
{
struct Student St[10] ;
int max, i, index ;
for ( i = 0 ; i < 5 ; i ++)
{
printf (“Input the Name & age of Student %d: ”, i + 1);
scanf (“%s %d”, St[i].name, &St[1].age);
}
max = St[0].age ;
for ( i = 0 ; i < 5 ; i ++)
{ if (max < St[i].age)
{
max = St[i].age ;
index = i ;
}
}
printf (“ The Elder Student is : %s ”, St[index].name);
}
An array of structres in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities. The array of structures in C are used to
store information about multiple entities of different data types. The array of structures is also
known as the collection of structures.
C provides us the feature of nesting one structure within another structure by using which,
complex data types are created.
Nested structure in C is nothing but structure within structure. One structure can be declared
inside other structure as we declare structure members inside a structure.
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.
Example
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s", emp.name, emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information....\n");
printf("Name: %s\n ", emp.name);
printf("City: %s\n Pincode: %d\n Phone: %s", emp.add.city, emp.add.pin, emp.add.phone);
}
• A structure can be passed to any function from main function or from any sub function.
• Structure definition will be available within the function only.
• It won’t be available to other functions unless it is passed to those functions by value or by
address(reference).
• 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.
struct student
{
int id;
char name[20];
float percentage;
};
void funcByValue (struct student record);
int main()
{
struct student record;
record.id = 1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
funcByValue (record);
return 0;
}
struct student
{
int id;
char name[20];
float percentage;
};
void funcByReference (struct student *);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
funcByReference (&record); // passes address
return 0;
}
void funcByReference (struct student *rec) //creates pointer and uses arrow operator
{
printf(" Id is: %d \n", rec→id);
printf(" Name is: %s \n", rec→name);
printf(" Percentage is: %f \n", rec→percentage);
}
2.10 Union
- A union is a special data type available in C that allows to store 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-purpose.
- Structures allocate enough space to store all their members, whereas unions can only hold
one member value at a time.
- Although union contains many members of different types, it can handle only one member
at a time unlike structure, because all the members share the same memory.
• Defining a Union
o To define a union, you must use the union keyword. The union keyword defines a new data
type, with more than one member.
o The format of the union statement is as follows
union unionName
{
dataType member1;
dataType member2;
---
dataType memberN;
};
• Example:
union Product
{
int id;
float price;
};
- Here union Product declares a union to hold the details of a Product which consists of two
data fields, namely id, and price. These fields are called union elements or members. Both
the fields share the memory.
• Memory allocation
union Product
{
float Price;
int Qty;
char ch;
} P1;
P1
ch
Qty
Price
Compiler allocates a piece of memory that is large enough to hold the largest data type variable in
the union.
• In C language, sizeof() operator is used to calculate the size of structure, variables, pointers or
data types. Data types could be pre-defined or user-defined.
• Using the sizeof() operator we can calculate the size of the structure straightforward to pass
it as a parameter.
struct stud {
int roll;
char name[10];
int marks;
};
int main() {
int size;
struct stud s;
size = sizeof(s);
printf("nSize of Structure : %d", size);
return(0);
}
• Structure Padding in C
Structure padding is a concept in C that adds the one or more empty bytes between the memory
addresses to align the data in memory.
Consider a structure declaration:
struct Demo {
int id; /* sizeof(int) = 4 and Padding of 4 bytes */
double price; /* sizeof(double) = 8 */
short int type; /* sizeof(short int) = 2 and Padding of 6
bytes */
};
id 4 bytes padding
price
struct Demo {
double price; /* sizeof(double) = 8 */
int id; /* sizeof(int) = 4 */
short int type; /* sizeof(short int) = 2 and Padding of 2 bytes */
};
price
2 bytes
id type
padding
o To access members of structure, we used the dot ‘.’ operator with structure variable.
o When we have a pointer of structure type, we use arrow -> to access structure members.
o Size of structure variable is 2 bytes.
• Example
C program with structure pointer.
.struct Product {
int id;
char name[10];
};
void main()
{
. struct Product *ptr; /* ptr has just 2 bytes allocated */
struct Product p1 = { 101, “Sony TV” }; /* p2 has 12 bytes allocated */
ptr = &p1;
printf(“ Product id = %d ”, ptr->id);
printf(“Product Name = %s ”, ptr->name);
}
• Memory diagram
P1
id 101