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

Pps Unit III (Structures)

Uploaded by

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

Pps Unit III (Structures)

Uploaded by

Varshith Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

UNIT-III

STRUCTURES
1.Definition and Initialization of Structures
2.Accessing structure members
3.NestedStructures
4.Array of Structures
5.Pointer to structure
6.Structures and Functions
7.Unions
8.typedef, Enumerated Datatypes.
Structure is a user-defined datatype in C language which allows
us to combine data of different types together
(OR)
Structure is a group of variables of different data types
represented by a single name.
It is somewhat similar to an Array, but an array holds data of
similar type only. But structure can store data of any type.
Structure in c is a user-defined data type that enables us to store
the collection of different data types. Each element of a
structure is called a member.
How to create (or) Define a structure in C:
We use struct keyword to create a structure in C.
Let's see the syntax to define the structure in c.
struct structure_name
{
data_type variable1;
data_type variable2;
.
.
data_type variableN;
};
Let's see the example to define a structure for an entity employee in c
struct employee
{
int id;
char name[20];
float salary;
};
Declaring Structure Variables:
Structure variable declaration is similar to the declaration of any normal
variable of any other datatype. Structure variables can be declared in
following two ways:
1) Declaring Structure variables separately:
struct Student
{
char name[25];
int age;
char branch[10];
char gender ;
};
struct Student S1, S2; //declaring variables of struct Student
2) Declaring Structure variables with structure definition:
struct Student
{
char name[25];
int age;
char branch[10];
}S1;
Here S1 and S2 are variables of structure Student. However this
approach is not much recommended.
Accessing members of the structure:
There are two ways to access structure members:
• By . (member or dot operator)
• By -> (structure pointer operator)
Suppose, you want to access the age of student
ex: s1.age
s1->age
Structure Initialization:
structure variable can also be initialized at compile time and runtime
1.Compile time Initialization:
struct patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //compiletime initialization
Note: The values for the value initialized structure should match the
order in which structure members are declared.
Invalid initialization:
struct student stu1 = { 12, "Pankaj", 79.5f };
(OR)
struct patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
printf(“height=%f\n”,p1.height);
printf(“weight=%d\n”p1.weight);
printf(“age=%d\n”,p1.age);
Ex:#include<stdio.h>
void main()
{
struct student
{
char name[100];
int rollno;
float marks;
};
struct student s1={“kiran”, 401,70.5};
// Print student details
printf("Student details\n");
printf("Name : %s\n", s1.name);
printf("Rollno : %d\n", s1.roll);
printf("Marks: %.2f\n", s1.marks);
}
2.Runt time Initialization:
Using runtime initialization user can get a chance of accepting or
entering different values during different runs of program.
A structure can also be initialized at runtime using scanf() function.
We can also use scanf() function to give values to the structure
members through keyboard
struct student
{
char name[100];
int rollno;
float marks;
};
struct student s1;
scanf(“%s”,s1.name);
scanf(“%d”,&s1.rollno);
scanf(“%f”,&s1.marks);
void main()
{
struct student
{
char name[100];
int roll;
float marks;
};
struct student s1;
printf("Enter student name: "); // Read student details from user
gets(s1.name);
printf("Enter student roll no: ");
scanf("%d", &s1.rollno);
printf("Enter student marks: ");
scanf("%f", &s1.marks);
// Print student details
printf("\n\nStudent details\n");
printf("Name : %s\n", s1.name);
printf("Roll : %d\n", s1.rollno);
printf("Marks: %.2f\n", s1.marks); }
Nested structures:
A structure inside another structure is called nested structure.
Syntax:
struct tagname_1
{
member1;
member2;
……….
membern;
struct tagname_2
{
member_1;
member_2;
...
member_n;
}var1 ;
} var2;
#include<stdio.h>
void main()
{
struct address
{
char city[20];
int pin;
char phone[14];
struct employee
{
char name[20];
}emp;
}add;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,add.city, &add.pin, add.phone);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,add.city,
add.pin,add.phone);
}
To access the members of the inner structure
var2.var1.member_1 - refers to the member_1 of structure tagname_2
var2.var1.member_2 - refers to the member_2 of structure tagname_2
Let's take an example:
struct student
{
struct person stu.p.name - refers to the name of the person

{ stu.rollno - refers to the rollno of the student


char name[20];
int age;
char dob[10];
}p;
int rollno;
float marks;
} stu;
Array of Structures:
we need to store the data of 5 students. We can store it by using
the array of structure .
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.
For example:
struct book b[10]; //10 elements in an array of structures of type
‘book’
Ex: struct student s[5];
#include<stdio.h>
void main()
{
struct student
{
int rollno
char name[10];
};
struct student st[5];
int i;
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter 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);
}
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
Structure using Pointer(Pointer to a Structure ):
A pointer is a variable which points to the address of another
variable of any data type like int, char, float etc. Similarly, we
can have a pointer to structures, where a pointer variable can
point to the address of a structure variable.
how we can declare a pointer to a structure variable.
EX: int a,*p; struct student s,*p;
p=&a; p=&s;
s is normal structure variable, p is pointer structure variable.
P is a ponter variable that can store the address of the variable
of type struct student.
We can now assign the address of variable s to pointer p using
& operator.
Now p points to the structure variable s
Accessing members using Pointer :
C structure can be accessed in 2 ways in a C program.
They are,
• Using normal structure variable
• Using pointer variable
There are two ways of accessing members of structure
using pointer:
1.Using indirection (*) operator and dot (.) operator.
2.Using arrow (->) operator or membership operator.
1.Using Indirection (*) Operator and Dot (.) Operator:
To access a member of structure write *p followed by
a dot(.) operator, followed by the name of the
member.
For example:
(*p).name - refers to the name of student
(*p).age - refers to the age of student
Parentheses are necessary because the precedence of
dot(.) operator is greater than that of indirection (*)
operator.
Using arrow operator (->):
C provides another way to access members using the
arrow (->) operator. To access members using arrow
operator write pointer variable followed by
-> operator, followed by name of the member.
Ex:
p->name // refers to the name of student
P->age// refers to the age of student
#include <stdio.h>
struct student
{
int id;
char name[30];
float percentage;
};
void main()
{
struct student s1 = {501, "Raju", 90.5};
struct student *ptr;
ptr = &s1;
printf("Record of STUDENT1: \n");
printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
}
How to Copy and Compare Structure Variables?

Two variables of the same structure type can be copied the same
way as ordinary variables. If person1 and person2 belong to the
same structure, then the following statements are valid.
Ex: 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.
Ex: person1 = = person2
person1 ! = person2
Statements are not permitted.
Ex: Program for comparison of structure variables
struct class
{
int no;
char name [20];
float marks;
}
void main ( )
{
int x;
struct class stu1 = { 111, “Rao”, 72.50};
struct class stu2 = {222, “Reddy”, 67.80};
struct class stu3;
stu3 = stu2;
x = ( ( stu3.no= = stu2.no) && ( stu3.marks = = stu2.marks))?1:0;
if ( x==1)
printf (“ \n student 2 & student 3 are same \n”);
else
printf ( “\n student 2 and student 3 are different “);
Structures and Functions in C:
C allows programmers to pass a single or entire structure
information to or from a function.
Like all other types, we can pass structures as arguments to a
function. In fact, we can pass, individual members, structure
variables, a pointer to structures etc to the function.
The structure variable may be passed as a value or reference.
Similarly, functions can return either an individual member or
structures variable or pointer to the structure.
PASSING STRUCTURE TO FUNCTION IN C:
It can be done in 2 ways.
• Passing structure to a function by value
• Passing structure to a function by address(reference)
1.PASSING STRUCTURE TO FUNCTION BY VALUE:
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.
There are two methods by which the values of the structures can be
transferred from one function to another .
Method 1:
The first method is to pass each member of a structure as actual
argument of the function call .
Ex: #include<stdio.h>
struct student
{
char name[20];
int age;
};
void display(char[],int); //function prototype
void main()
{
struct student s;
printf(“enter name and age of the student”);
scanf(“%s%d”,s.name,&s.age);
display(s.name,s.age);
}
void display(char str[],int a)
{
printf(“name :%s\n” ,str);
printf(“age :%d\n” ,a);
}
Method 2:
In this method, the whole structure is passed to a function by
value.
#include <stdio.h>
struct student
{
char name[50];
int age;
};
void display(struct student s); //function prototype
int main()
{
struct student s1;
printf("Enter name: ");
gets(s1.name);
printf("Enter age: ");
scanf("%d", &s1.age);
display(s1); // passing struct as an argument
}
void display(struct student s)
{
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
}
Output: Enter name: kittu
Enter age: 30
Displaying information
Name: kittu
Age: 30
2. PASSING STRUCTURE TO FUNCTION BY ADDRESS:
 The Call by value method is inefficient to pass the large structures
to functions. C provides the efficient method, known as call by
reference to pass large structures to functions. Call by reference
method is achieved by passing pointers to functions. Pointer is a
variable, used to hold or store the address of another variable.
 In this method, the address of the structure is passed to the function.
Any changes made to the structure members are reflected to the
original structure.
EX: #include<stdio.h>
struct student
{
char name[20];
int age;
};
void display(struct student *p); //function prototype
void main()
{
struct student s={“kittu,20};
display(&s); //function call
}
void display(struct student *p)
{
printf(“Name :%s\n”,p->name);
printf(“Age :%d\n”,p->age);
}
Passing one dimensional string to a function:
To pass a one dimensional string to a function as an argument we just
write the name of the string array variable.
EX: Write a function to read and print string
#include <stdio.h>
void display(char []);
void main()
{
char str[] = "Hello World";
display(str);
}
void display(char str1[])
{
printf("String: %s\n", str1);
}
Passing One-dimensional array to a function:
//Write a function to read and print 1-D array elements
#include<stdio.h>
void main()
{
int a[5]={10,20,30,40,50};
void display(int a[]);
display(a);
}
void display(int a[])
{
int i;
for(i=0;i<5;i++)
printf(“%d\n”,a[i]);
}
Union in C
 Like Structures, union is a user defined data type. In union
all members share the same memory location.

 The only differences is in terms of storage

 In structure each member has its own storage location,


whereas all members of union uses a single shared memory
location which is equal to the size of its largest data member.

 Structures allocate enough space to store all their members,


whereas unions can only hold one member value at a time.
How to define a union?
The union keyword is used to define the union. Let's see the syntax to
define union in c.
union union_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Let's see the example to define union for an employee in c.
union employee
{
int id;
char name[50];
float salary;
};
Create union variables:
• When a union is defined, it creates a user-defined type.
However, no memory is allocated. To allocate memory for a
given union type and work with it, we need to create variables.
• Here's how we create union variables.
union employee
{
int id;
char name[50];
float salary;
};
union employee e1,e2,e3;
Here,e1,e2,e3 are union variables
Access members of a union:
Syntax for accessing any union member is similar to accessing
structure members,
• We use the . operator to access members of a union. And to
access pointer variables, we use the -> operator.
union test
{
int a;
float b;
char c;
}t;
t.a; //to access members of union t
t.b;
t.c;
Ex 1:
#include <stdio.h>
void main()
{
union Job
{
float salary;
int workerNo;
} j;
j.salary = 12.3;
j.workerNo = 100;
printf(Salary = %f\n", j.salary);
printf("Number of workers = %d", j.workerNo);
}
EX 2:
#include<stdio.h>
union data
{
int i;
float f;
char str[20];
};
void main( )
{
union data d;
d.i = 10;
d.f = 220.5;
strcpy( d.str, "C programming”);
printf( "data.i : %d\n", d.i);
printf( "data.f : %f\n", d.f);
printf( "data.str : %s\n", d.str);
}
Advantage of union over structure:
It occupies less memory because it occupies the size of the largest
member only.
Disadvantage of union over structure:
Only the last entered data can be stored in the union. It overwrites
the data previously stored in the union, the existing data is
replaced with new data.
Advantages of union:
• It occupies less memory compared to structure.
• When you use union, only the last variable can be directly
accessed.
• Union is used when you have to use the same memory location
for two or more data members.
• It enables you to hold data of only one data member.
Enumeration (or enum) in C:
 The enum in C is also known as the enumerated type. It is a
user-defined data type that consists of integer values, and it
provides meaningful names to these values. The use of enum in
C makes the program easy to understand and maintain. The
enum is defined by using the enum keyword.
 It is used to assign names to the integral constants
Here is the syntax of enum in C language
syntax: enum enum_name{const1, const2, ....... };
In the above declaration, The default value of const1 is 0,
const2 is 1, and so on. We can also change the default value of
the integer constants at the time of the declaration.
Ex1: enum color{red,green,black,blue};
• For example:
enum fruits{mango, apple, strawberry, papaya};
• The default value of mango is 0, apple is 1, strawberry is 2, and papaya is
3. If we want to change these default values, then we can do as given
below:
enum fruits{mango=2, apple=1, strawberry=5, papaya=7};
Ex: #include <stdio.h>
void main()
{

enum months{jan=1, feb, march, april, may, june, july, august, september,
october, november, december};
// printing the values of months
for(int i=jan;i<=december;i++)
{
printf("%d, ",i);
}
o/p:
Declaration of enum variables:
syntax: enum enumname var1,var2……varn;
Ex: enum week day1,day2;
Here day1,day2 are the variables of type enum
#include <stdio.h>
void main()
{
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday,
Friday, Saturday};
enum week today;
today = Wednesday;
printf("Day %d",today+1);
}
o/p:
• 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.

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

• The values assigned to the enum names must be


integral constant, i.e., it should not be of other types
such string, float, etc.
typedef in C
 typedef is a keyword used in C language to assign alternative names
to existing datatypes.
 The typedef is an advance feature in C language which allows us to
create an alias or new name for an existing type or user defined type.
Syntax of typedef:
typedef <existing_name> <alias_name>
In the above syntax, 'existing_name' is the name of an already
existing variable while 'alias name' is another name given to the
existing variable.
Ex: typedef unsigned int unit;
we can create the variables of type unsigned int by writing the
following statement:
Ex: unit a, b;
instead of writing:
unsigned int a, b;
Let's understand through a simple example.
#include <stdio.h>
void main()
{
typedef unsigned int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
}

You might also like