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

Unit 9 Structure & Uniuon

The document discusses structures in C programming. It explains what structures are, how to define and declare them, initialize structure variables, pass structures to functions, use nested and pointer to structures. It also covers arrays of structures and unions.

Uploaded by

Sakar Sapkota
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Unit 9 Structure & Uniuon

The document discusses structures in C programming. It explains what structures are, how to define and declare them, initialize structure variables, pass structures to functions, use nested and pointer to structures. It also covers arrays of structures and unions.

Uploaded by

Sakar Sapkota
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Structure in C

Why we need Structure in C?


If we have to write a program to store Student information, which will have Student's
name, age, branch, permanent address, father's name etc. which included string values,
integer values etc. how can I use arrays for this problem, I will require something which
can hold data of different types together.
i.e :- Structure.

Structure
 Structure is the way to group the variable.
 Structure is the collection of similar & disimmilar elements.
 Defining structure means creating new datatype.
 In structure, data is stored in the form of records.

Defining a Structure
Syntax

struct structure_name
{
// variable declaration here
(member variable)
};
Memory Consumption
 No memory is consumed for a definition of structure.
 For memory consumption, we need to declare the variable of type structure.

Declaration of Structure Variable

Initialization of Structure Variable


 We can initialize the variable at the time of declaration.
 We can also initialize the variable after the declaration.
Taking Input from User
struct date{
int d,m,y;
};
void main()
{
struct date d1;
printf(“Enter Today’s date\n ”);
scanf(“%d/%d/%d” ,&d1.d,&d1.m,&d1.y);
printf(“Today’s date :”,d1.d,d1.m,d1.y);
getch();
}

Array Of Structure
An array of structures in C can be defined as the collection of multiple structures variables
at a same time where each variable contains information about different entities.
The array of structures in C is used to store information about multiple entities of different
data types at a same time. The array of structures is also known as the collection of
structures.

Without Array of Structure


Store the data of 5 Student
#include<stdio.h>
struct student
{
char name[20];
int id;
float marks;
};
void main()
{
struct student s1,s2,s3;
int dummy;
printf("Enter the name, id, and marks of student 1 ");
scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
scanf("%c" ,&dummy);
printf("Enter the name, id, and marks of student 2 ");
scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
scanf("%c" ,&dummy);
printf("Enter the name, id, and marks of student 3 ");
scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
scanf("%c" ,&dummy);
printf("Printing the details....\n");
printf("%s %d %f\n",s1.name,s1.id,s1.marks);
printf("%s %d %f\n",s2.name,s2.id,s2.marks);
printf("%s %d %f\n",s3.name,s3.id,s3.marks);
}

In the above program, we have stored data of 3 students in the structure. However, the
complexity of the program will be increased if there are 20 students. In that case, we will
have to declare 20 different structure variables and store them one by one.
This will always be tough since we will have to declare a variable every time we add a
student.

#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("\nEnter Name:");
scanf("%s" ,&st[i].name);
}
printf("\n Student Information List:");
for(i=0;i<5;i++){
printf("\n Rollno:%d, Name:%s" ,st[i].rollno, st[i].name);
}
return 0;
}

Nested Structure
One Structure inside another structure is known as the nested structure.
C provides us the feature of nesting one structure within another structure by using which,
complex data types are created.

The structure can be nested in the following ways.

1. By separate structure
2. By Embedded structure
1) Separate structure
Here, we create two structures, but one (dependent) structure should be used inside
another (main) structure as a member.

Example:-

struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;

doj is the variable of type Date. Here doj is used as a member in Employee structure.
In this way, we can use Date structure in many structures.

2) Embedded structure
The embedded structure enables us to declare the structure inside the structure. Hence,
it requires less line of codes but it cannot be used in multiple data structures.

Example:-
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;

Accessing Nested Structure


We can access the member of the nested structure by
Outer_Structure.Nested_Structure.member as given below:

emp1.doj.dd
emp1.doj.mm
emp1.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;
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Bishal Patel"); //copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;

//printing first employee information


printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e
1.doj.yyyy);
return 0;
}
Output
Employee id : 101
Employee name : Bishal Patel
Employee date of joining (dd/mm/yyyy) : 10/11/2014

Passing structure to function


Just like other variables, a structure can also be passed to a function. We may pass the
structure members into the function or pass the structure variable at once.

Consider the following example to pass the structure variable employee to a function
display() which is used to display the details of an employee.

Eg:-
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void display(struct employee);
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);
display(emp);
}
void display(struct employee emp)
{
printf("Printing the details....\n");
printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}
Output
Enter employee information?
Bishal
Birgunj
44300
9817206112
Printing the details….
Bishal Birgunj 44300 9817206112
Passing Array of Structure to a Function
In this C program, we are going to learn how to pass an array of structure to a user
define function? Here, we are an example, where we are passing a structure to a
function in C.
Given an array of structure and we have to pass it to the function in C.

Structure declaration

struct exam
{
int roll;
int marks;
char name[20];
};

struct exam obj[2];

obj is an array of structure for 2 structures.

Assigning values to the structure variables (array of structure variables) inside the main()

// assign values using the object 1

obj[0].marks = 35;

obj[0].roll = 10;

strcpy(obj[0].name , "Arjun kapoor");

// assign values using the object 1

obj[1].marks = 75;

obj[1].roll = 11;

strcpy(obj[1].name , "Balram chauhan");

Function calling statement,

structfun(obj);

Here, obj is an array of structure.


Program
#include<string.h>
#include <stdio.h>
struct exam
{
int roll;
int marks;
char name[20];
};

struct exam obj[2];


void structfun(struct exam *obj);
void structfun(struct exam *obj)
{
printf("\nName is : %s",obj[0].name);
printf("\nRoll No. is : %d",obj[0].roll);
printf("\nMarks are : %d",obj[0].marks);

printf("\n");

printf("\nName is : %s",obj[1].name);
printf("\nRoll No. is : %d",obj[1].roll);
printf("\nMarks are : %d",obj[1].marks);
}

int main()
{
obj[0].marks = 35;
obj[0].roll = 10;
strcpy(obj[0].name , "Arjun kapoor");

obj[1].marks = 75;
obj[1].roll = 11;
strcpy(obj[1].name , "Balram chauhan");

structfun(obj);

return 0;
}
Pointer to Structure
The structure pointer points to the address of a memory block where the Structure is
being stored. we use a structure pointer which tells the address of a structure in memory
by pointing pointer variable ptr to the structure variable.

Declare a Structure Pointer


The declaration of a structure pointer is similar to the declaration of the structure variable.
So, we can declare the structure pointer and variable inside and outside of the main()
function.

struct structure_name *ptr;

Initialization of the Structure Pointer


ptr = &structure_variable;
struct structure_name *ptr = &structure_variable;

Access Structure member using pointer


There are two ways to access the member of the structure using Structure pointer:

1. Using (*) asterisk or indirection operator and dot (.) operator.


2. Using arrow (->) operator or membership operator.

Program
#include <stdio.h>
#include <string.h>
struct Subject
{
char sub_name [30];
int sub_id;
char sub_duration [50];
char sub_type [50];
};
int main ()
{
struct Subject sub;
struct Subject *ptr;
ptr = & sub;

strcpy (sub.sub_name, " Computer Science");


sub.sub_id = 1201;
strcpy (sub.sub_duration, "6 Months");
strcpy (sub.sub_type, " Multiple Choice Question");

// print the details of the Subject;


printf (" Subject Name: %s\t ", (*ptr).sub_name);
printf (" \n Subject Id: %d\t ", (*ptr).sub_id);
printf (" \n Duration of the Subject: %s\t ", (*ptr).sub_duration);
printf (" \n Type of the Subject: %s\t ", (*ptr).sub_type);

return 0;
}

Union
 Union is the same as a structure the only difference is that in memory allocation.
 Structure variable allocates total number of memory for all data types used in the
structure.
 Union only allocates only one memory location for all data type.

Defining a Union
Syntax

union union_name
{
// variable declaration here
(member variable)
};

Eg:-
Eg:-

union abc
{
int a;
char b;
float c;
double d;
};
int main()
{
printf("Size of union abc is %d", sizeof(union abc));
return 0;
}

Accessing member of union


We can access union in the same way as a structure.
#include<stdio.h>
union abc
{
int a;
char b;
float c;
double d;
};
int main()
{
union abc x;
printf("Size of a is %d\n", sizeof(x.a));
printf("Size of b is %d\n", sizeof(x.a));
printf("Size of c is %d\n", sizeof(x.a));
printf("Size of union abc is %d\n", sizeof(union abc));
return 0;
}

Accessing members of union using pointers


We can also access the members of the union through pointers by using the (->) arrow
operator.

union abc
{
int a;
char b;
float c;
double d;
};
int main()
{
union abc *x;
printf("Size of a is %d", sizeof(x->a));
printf("Size of b is %d", sizeof(x->a));
printf("Size of c is %d", sizeof(x->a));
printf("Size of union abc is %d", sizeof(union abc));
return 0;
}

Enumeration
Enumeration (or enum) is a user defined data type in C. It consists of constant integrals
or integers that are given names by a user.

It is mainly used to assign names to integral constants, the names make a program easy
to read and maintain.

It is created by using enum keyword.


Syntax:
enum enum_name
{
const1, const2, const3, …. constN
};
#include<stdio.h>
enum month
{
Jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
};
int main()
{
enum month m1;
m1 = feb;
printf("%s" ,m1);
return 0;
}
Output
1
 Here, we have created enum datatype in which it contains 12 constant integers to
which we have given name as jan feb …. Nov.
 By default it will start from 0 to n-1. But we can give the different values to these
constants.
 We can separate the list of constant by commas(,).
 We can only take these 12 values to process.

You might also like