0% found this document useful (0 votes)
7 views

Module 2 Structures

Uploaded by

mohansharan486
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Module 2 Structures

Uploaded by

mohansharan486
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Module-2: Structures

Module2: Structures
• Defining a structure

• Declaring structure variable

• Accessing structure members

• Structure initialization

• Copying and comparing structure variables.

• Operations on individual members

• Array of structures

• Structure within structure

• Structure and functions

• Union

• Size of structure

Prof. Vishwanath Murthy, MCA, RNSIT 1


Module-2: Structures

2.1. Defining a 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.

Prof. Vishwanath Murthy, MCA, RNSIT 2


Module-2: Structures

2.2 Creating structure variables

Structure variables can be declared in following two ways:


1. Declaring Structure variables separately
2. Declaring Structure variables with structure definition

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;

2. Declaring Structure variables with structure definition

.struct Product { Creates two structure variables


char type; var1 and var2, each of variables
contain two fields type and cost.
int cost;
} s1, s2;

• Memory representation

s1 s2

type type

cost cost

Prof. Vishwanath Murthy, MCA, RNSIT 3


Module-2: Structures

2.3 Accessing structure members


Structure members can be accessed and assigned values in several ways. Structure members have
no meaning individually without the structure. In order to assign a value to any structure member,
the member name must be linked with the structure variable using a dot ‘.’ operator also
called period or member access operator
Syntax:
strcureVariable.memberName

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);
}

Prof. Vishwanath Murthy, MCA, RNSIT 4


Module-2: Structures

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);

if( st.test1 > st.test2)


{
if( st.test1 > st.test3 )
top1 = st.test1;
else
top2 = st.test3;
}

if( st.test2 > st.test1)


{
if( st.test2 > st.test3 )
top1 = st.test2;
else
top2=st.test3;
}

if( st.test3 > st.test1)


{
if( st.test3 > st.test1 )
top1 = st.test2;
else
top2=st.test3;
}
printf (“Best 2 tests are : t1 = %d and t2 = %d \n”, top1, top2);
avg = (top1 + top2) / 2;
printf (“Average = %d \n”, avg );
}

Prof. Vishwanath Murthy, MCA, RNSIT 5


Module-2: Structures

2.4 Initializing Structure

Structure members can be initialized using curly braces ‘{}’.


Syntax:
struct structureName structureVariable = { expression , ... }

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);

• Rules for Initialization structure


There are few rules to keep in mind while initializing structure variables at compile-time.
1. Cannot initialize individual members inside the structure template.
2. Order of initialization: The order of values enclosed in braces must match the order of
members in the structure definition.
3. Partial initialization: We can initialize only the first few members and leave the remaining
blank. The uninitialized members should be only at the end of the list.
4. Uninitialized members: Uninitialized members will be assigned default values,
i.e – Zero for integer and floating point numbers and ‘\0’ for characters and strings

Prof. Vishwanath Murthy, MCA, RNSIT 6


Module-2: Structures

2.5 Copying and comparing structure variables.

• 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 “);
}

Above example demonstrates:


• copying structure variables
• comparing structure variables

Prof. Vishwanath Murthy, MCA, RNSIT 7


Module-2: Structures

2.6 Operations on individual members

• 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.

C Program to Add Two Complex Numbers by Passing Structure to a Function

#include <stdio.h>
typedef struct complex {
float real;
float imag;
} complex;

complex add(complex n1, complex n2);

int main() {
complex n1, n2, result;

printf("For 1st complex number \n");


printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n1.real, &n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n2.real, &n2.imag);

result = add(n1, n2);

printf("Sum = %.1f + %.1fi", result.real, result.imag);


return 0;
}

complex add(complex n1, complex n2) {


complex temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return (temp);
}

Prof. Vishwanath Murthy, MCA, RNSIT 8


Module-2: Structures

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);
}

Prof. Vishwanath Murthy, MCA, RNSIT 9


Module-2: Structures

2.7 Array of structures

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.

an array of structures that stores information of 5 students and prints it.


#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\n Enter Rollno:");
scanf("%d", &st[i].rollno);
printf("\n Enter Name:");
scanf("%s", &st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s", st[i].rollno, st[i].name);
}
}

Prof. Vishwanath Murthy, MCA, RNSIT 10


Module-2: Structures

2.8 Structure within structure

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);
}

Prof. Vishwanath Murthy, MCA, RNSIT 11


Module-2: Structures

2.9 Structure and functions

• 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.

Passing structure to function can be done in below 3 ways.


1. Passing structure to a function by value
2. Passing structure to a function by address(reference)
3. No need to pass a structure – Declare structure variable as global

1. Passing structure to function in c by val


• If the structure is passed to the function by the value, then Changes made to the structure
variable members within the function will not reflect the original structure members of calling
program..
• Example:

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;
}

Prof. Vishwanath Murthy, MCA, RNSIT 12


Module-2: Structures

void funcByValue (struct student rec)


{
printf(" Id is: %d \n", rec.id);
printf(" Name is: %s \n", rec.name);
printf(" Percentage is: %f \n", rec.percentage);
}

2. Passing structure to a function by address(reference)


• If the structure is passed to the function by the reference, then Changes made to the structure
variable members within the function will directly reflect the original structure members of
calling program.
• Example:

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);
}

Prof. Vishwanath Murthy, MCA, RNSIT 13


Module-2: Structures

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.

Prof. Vishwanath Murthy, MCA, RNSIT 14


Module-2: Structures

• 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.

Prof. Vishwanath Murthy, MCA, RNSIT 15


Module-2: Structures

2.11 Size of structure

• 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.

Program to find size of structure


#include<stdio.h>

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);
}

Prof. Vishwanath Murthy, MCA, RNSIT 16


Module-2: Structures

• 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 */
};

• Memory diagram with padding:

id 4 bytes padding

price

type 6 bytes padding

Size = sizeof(struct Demo); // returns Size = 24

• Rewrite the structure:

struct Demo {
double price; /* sizeof(double) = 8 */
int id; /* sizeof(int) = 4 */
short int type; /* sizeof(short int) = 2 and Padding of 2 bytes */
};

• Memory diagram with padding:

price

2 bytes
id type
padding

Size = sizeof(struct Demo); // returns Size = 16

Prof. Vishwanath Murthy, MCA, RNSIT 17


Module-2: Structures

2.12 Pointers to structure

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

ptr 100 name Sony TV


Stack
100

Prof. Vishwanath Murthy, MCA, RNSIT 18


Module-2: Structures

• Difference between structure and union

Prof. Vishwanath Murthy, MCA, RNSIT 19

You might also like