Pps Unit III (Structures)
Pps Unit III (Structures)
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
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.
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.