0% found this document useful (0 votes)
50 views33 pages

Structures and Union

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

Structures and Union

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

UNIT 4 STRUCTURES AND UNION

Structure - Nested structures – Pointer and Structures – Array of structures – Example


Program using structures and pointers – Self referential structures – Dynamic memory
allocation - Singly linked list – typedef-union storage classes and visibility

STRUCTURES:
 A structure is a user-defined data type that can store related information together. A
structure is acollection of variables under a single name.
 the major difference between a structure and an array is that, an array contains
related informationof the same data type.
 The variables within a structure are of different data types and each has a name that is
used to selectit from the structure.
Features of structures
 Structures can store more than one different data type data under
a single variable.
 Structure elements are stored in successive memory locations.
 Nesting of structure is possible.
 Structure elements can be passed as argument to the function.

Syntax:
//Structure creation
struct structurename
{
Datatype1
variablename;Datatype2
variablename;
.
.
};

//Object Creation

struct structname objname;


 It is possible to create structure pointers.
Example ://Program to display a point

#include<stdio.h>struct point

int x,y;

};

void main()
Output:
{ (2,3)

struct point p1={2,3}; printf(“(%d,

%d)”,p1.x,p1.y);

Initialization of structures:

Syntax:
struct struct_name

datatype membername1;

datatype membername2;

datatype membername3;

}sturct_var={constant1,constant2,constant3,….};

Example:
struct student
{

int rno;

char name[20];

char course[20];

float fees;

}stud1={01,”Rahul”,”BCA”,45000};

or

struct student stud2={02,”Rajiv”};

Fig. illustrates how the values will be assigned to individual fields of the structure

Accessing the members of a structure:


A structure member variable is generally accessed using a ‘.’(dot) operator.
Syntax:
struct_var.membername;

Example:

stud1.rno=01; stud1.name=”Rahul”;stud1.course=”BCA”;stud1.fees=45000;

Receiving user input:

scanf(“%d”,&stud1.rno);

scanf(“%s”,stud1.name);

Displaying output:

printf(“Roll No:%d”,stud1.rno);printf(“Name:%s”,stud1.name);

TYPEDEF DECLARATION:
The typedef keyword enables the programmer to create a new data type name
from an existing data
type.
Syntax:
typedef existingdatatype newdatatype;
Example 1:

typedef int INTEGER;INTEGER number=5;

Example 2:

typedef struct student

int rno;
char name[20]; char course[20];float fees;

};

student s1; //instead of struct student s1;

COPYING AND COMPARING STRUCTURES:

Values of structure variables

Copy

We can assign a structure to another structure of the


same type.struct student
stud1={01,”Rahul”,”BCA”,45000};
struct student stud2=stud1;

Compare:

if(stud1.fees==stud2.fees)
printf(“Fees of s2 and s1 are equal”);
STRUCTURES WITHIN STRUCTURES (NESTED STRUCTURES) :
 Structures can be placed within another structures ie., a structure may contain another
structure as itsmember. A structure that contains another structure as its member is
called as nested structures.

Example:write a c program to read and display information of students using


nested structure
#include<stdio.h>
int main()
{
int day;
int month;
int year;
};struct student
{
int rollno;
char no[100];
float fees;
struct DOB date;
};
struct student stud1;
clrscr();
printf(“enter the roll no”);
scanf(“%d”,&stud1.roll_no);
printf(“enter the name”);
scanf(“%s”,stud1.name);
printf(“enter the fees”);
scanf(“%f “,&stud1.fees);
printf(“enter the DOB”);
printf(“%d%d%d”,&stud1.date.day,&stud1.date.month,&stud1.date.year); Printf(“\
n ******students details******”);
Printf(“\n ROLL No=%d”,stud1.roll_no);
Printf(“\n NAME=%s”,stud1.name); Printf(“\
n FEES = %f”,stud1.fees);
Printf(“\n DOB =%d-%d-%d”,stud1.date.day,stud1.date.month,stud1.date.year);
getch();
return 0;
}
Output:
Enter the roll no 01
Enter the name arun
Enter the fees 45000
Enter the DOB 25-09-1991
ARRAYS OF STRUCTURES.
In the above examples, we have seen how to declare a structure and assign
values to its datamembers.
PASSING STRUCTURES THROUGH POINTERS:
 Passing large structures to functions using the call by value method is very inefficient.
Therefore, it is preferred to pass structures through pointers. It is possible to create a
pointer to almost any type in C, including the user-defined types.
 It is extremely common to create pointers to structures. A pointer to a structure is a
variable that holds the address of a structure. The syntax to declare a pointer to a
structure can be given as,

struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................
}*ptr;

Or

struct struct_name *ptr;


 For our student structure, we can declare a pointer variable by writing
 struct student *ptr_stud, stud;

 The next thing to do is to assign the address of stud to the pointer using the
address operator(&), as we would do in case of any other pointer. So to assign the
address, we will write
 ptr_stud = &stud;
 To access the members of a structure, we can write
(*ptr_stud).roll_no;
Write a program to initialize the members of a structure by using a pointer to the
structure.
#include<stdio.h>

#include <conio.h>

struct student
{
int r_no; Output
char name[20]; Enter the details of the

char course[20]; student: Enter the

RollNumber = 02 Enter the


int fees;
Name = Aditya Enter the
};
Course = MCA Enter the Fees
int main()
= 60000
{ DETAILS OF THE STUDENT

struct student stud1, *ptr_stud1;


clrscr();
ptr_stud1 = &stud1;
printf("\n Enter the details of the student : ");
printf("\n Enter the Roll Number =");
scanf("%d", &ptr_stud1 -> r_no); printf("\
n Enter the Name = ); gets(ptr_stud1 ->
name);
printf("\n Enter the Course = ");
gets(ptr_stud1 -> course);
printf("\n Enter the Fees = ");
scanf("%d", &ptr_stud1 -> fees);
printf("\n DETAILS OF THE STUDENT");
printf("\n ROLL NUMBER = %d", ptr_stud1 –>
r_no); printf("\n NAME = %s", ptr_stud1 –> name);
printf("\n COURSE = %s", ptr_stud1 –> course);
printf("\n FEES = %d", ptr_stud1 –> fees);
return 0;
}

SELF-REFERENTIAL STRUCTURES
Self-referential structures are those structures that contain a reference to the data
of its same type. That is, a self-referential structure, in addition to other data, contains a pointer to
a data that is of the sametype as that of the structure. For example, consider the structure node
given below.
struct node
{
int val;
struct node *next;
};
Here, the structure node will contain two types of data: an integer val and a pointer
next. You must be wondering why we need such a structure. Actually, self-referential
structure is the foundation of other data structures. We will be using them throughout this
book and their purpose will be clearer to you when we discuss linked lists, trees, and
graphs.

LINKED LISTS
Array is a linear collection of data elements in which the elements are stored in
consecutive memorylocations. Its size is fixed.
A linked list does not store its elements in consecutive memory locations and the user can
add anynumber of elements to it.
However, unlike an array, a linked list does not allow random access of data. Elements in a
linked listcan be accessed only in a sequential manner. But like an array, insertions and deletions
can be done at any point in the list in a constant time.
A linked list can be perceived as a train or a sequence of nodes in which each node contains one
ormore data fields and a pointer to the next node

Start

Simply linked list

Since in a linked list, every node contains a pointer to another node which is of the same type, it is
also called a self-referential data type.

START - stores the address of the first node in the list


.next - stores the address of its succeeding node.

Declaration of node:
struct node
{
int data;
struct node *next;
}

Memory Allocation and De-allocation for a Linked List


The Function malloc is most commonly used to attempt to ``grab'' a continuous portion of
memory. It is defined by:
void *malloc(size_t number_of_bytes);

it is usual to use the sizeof() function to specify the number of bytes:

Struct node *new_node;


new_node = (struct node*)malloc(sizeof(struct node));
SINGLY LINKED Lists
A singly linked list is the simplest type of linked list in which every node contains some data
and a pointer to the next node of the same data type. By saying that the node contains a pointer to
the next node,we mean that the node stores the address of the next node in sequence.
A singly linked list allows traversal of data only in one way. Figure 6.7 shows a singly linked
list.

START

Singly linked list

Inserting a New Node in a Linked List


In this section, we will see how a new node is added into an already
existing linked list. We willtake four cases and then see how insertion is done in
each case.
Case 1: The new node is
inserted at the beginning.
Case 2: The new node is
inserted at the end.
Case 3: The new node is inserted after a given node

Case 1: Inserting a Node at the Beginning of a Linked List

.
struct node *insert_beg(struct node *start)
{
struct node *new_node;int num;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;
new_node -> next = start;
start = new_node;
return start;
}

Case 2: Inserting a Node at the End of a Linked List

struct node *insert_end(struct node *start)


{
struct node *ptr, *new_node;
int num;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;
new_node -> next = NULL;
ptr = start;
while(ptr -> next != NULL)ptr = ptr -> next;
ptr -> next = new_node;
return start;
}

case 3: Inserting a Node After a Given Node in a Linked List


struct node *insert_after(struct node *start)
{
struct node *new_node, *ptr, *preptr;
int num, val;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
printf(“\n Enter the value after which the data has to be inserted : “);
scanf(“%d”, &val);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;
ptr = start;
preptr =
ptr;
while(preptr -> data != val)
{
preptr = ptr;
ptr = ptr -> next;
}
preptr -> next=new_node;
new_node -> next = ptr;
return start;
}
Deleting a Node from a Linked List:
Case 1: The first node is deleted.
Case 2: The last node is deleted.
Case 3: The node equal to a given value is deleted.

Case 1: Deleting the First Node from a Linked List

struct node *delete_beg(struct node *start)


{
struct node *ptr;ptr = start;
start = start -> next;free(ptr);
return start;
}
Case 2: Deleting the Last Node from a Linked List

struct node *delete_end(struct node *start)


{
struct node *ptr, *preptr;ptr = start;
while(ptr -> next != NULL)
{
preptr = ptr;
ptr = ptr -> next;
}
preptr -> next = NULL;free(ptr);
return start;
}
Case 3: Deleting the Node equal to a Given Value in a Linked List

struct node *delete_node(struct node *start)


{
struct node *ptr, *preptr;
int val;
printf(“\n Enter the value of the node which has to be deleted :
“); scanf(“%d”, &val);
ptr = start;
if(ptr -> data == val)
{
start = delete_beg(start);
return start;
}
else
{

while(ptr -> data != val)


{
preptr = ptr;
ptr = ptr -> next;
}
preptr -> next = ptr -> next;
free(ptr);
return start;
}

Programming Example
Declare a structure to store information of a particular date.
struct date
{
int day;
int month;
int year;
};

Declare a structure to create an inventory record.


struct inventory
{
char prod_name[20];
float price;
int stock;
};

Write a program, using an array of pointers to a structure, to read and display the data of
students.
#include <stdio.h>
#include <conio.h>

#include <alloc.h>

struct student

int r_no;

char name[20];

char course[20];

int fees;

};

struct student *ptr_stud[10];

int main()

int i, n;

printf("\n Enter the number of students : ");

scanf("%d", &n);
for(i=0;i<n;i++)
{
ptr_stud[i] = (struct student *)malloc(sizeof(struct student)); printf("\
nEnter the data for student %d ", i+1);
printf("\n ROLL NO.: ");
scanf("%d", &ptr_stud[i]–>r_no);
printf("\n NAME: ");
gets(ptr_stud[i]->name); printf(“\
ncourse”);
gets(ptr->stud[i]->course);
printf(“/n FEES”);
scanf(“%d”,&ptr_stud[i]->fees);
}
printf(“\n DETAILS OF STUDENT”);
for(i=0;i<n;i++)
{
printf((“\n ROLL NO=%d”,ptr.stud[i]->r.no);
printf(“\n NAME=%s,ptr->stud[i]->name);
printf(“\n COURSE=%s,ptr->stud[i]->course);
printf(“n FEES=%d”,ptr->stud[i]->fees);
}
return 0;
}

Output
Enter the number ofstudents : 1
Enter the data forstudent 1
ROLL NO.: 01
NAME: Rahul
COURSE:BCA
FEES: 45000
DETAILS OF STUDENT
SROLL NO. = 01
NAME = Rahul
COURSE = BCA
FEES = 45000

Write a program that passes a pointer to a structure to a function.


#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct student
{
int r_no;
char name[20];
char course[20];
int fees;
};
void display (struct student *);
int main()
{
struct student *ptr;
ptr = (struct student *)malloc(sizeof(struct student));
printf("\n Enter the data for the student ");
printf("\n ROLL NO.: ");
scanf("%d", &ptr–>r_no);
printf("\n NAME: ");
gets(ptr–>name);
printf("\n COURSE:
"); gets(ptr–>course);
}
printf(“/n FEES”);

scanf("%d", &ptr–>fees);
display(ptr);
getch();
return
}

void display(struct student *ptr)


{
printf("\n DETAILS OF STUDENT");
printf("\n ROLL NO. = %d", ptr–>r_no);
printf("\n NAME = %s", ptr–>name);
printf("\n COURSE = %s ", ptr–>course);
printf("\n FEES = %d", ptr–>fees);
}
Output
Enter the data for thestudent
ROLL NO.: 01
NAME: Rahul
COURSE: BCA
FEES: 45000
DETAILS OF STUDENTROLL NO. = 01
NAME = Rahul
COURSE = BCA
FEES = 45000
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.

Defining a Union

To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows −

union [union tag] {


member definition;
member definition;
...
member definition;
} [one or more union variables];

The union tag is optional and each member definition is a normal variable definition, such as int
i; or float f; or any other valid variable definition. At the end of the union's definition, before the
final semicolon, you can specify one or more union variables but it is optional. Here is the way
you would define a union type named Data having three members i, f, and str −

union Data {
int i;
float f;
char str[20];
} data;

Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string. The following example
displays the total memory size occupied by the above union −

#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;
}

When the above code is compiled and executed, it produces the following result −

Memory size occupied by data : 20


Accessing Union Members

To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we
wish to access. You would use the keyword union to define variables of union type. The
following example shows how to use unions in a program −
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

data.i = 10;
printf( "data.i : %d\n", data.i);

data.f = 220.5;
printf( "data.f : %f\n", data.f);

strcpy( data.str, "C Programming");


printf( "data.str : %s\n", data.str);

return 0;
}
Output
data.i : 10
data.f : 220.500000
data.str : C Programming
Accessing members of union using pointers

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

#include <stdio.h>

union abc
{
int a;
char b;
};
int main() output
{ 90
union abc *ptr; // pointer variable declaration
union abc var;
var.a= 90;
ptr = &var;
printf("The value of a is : %d", ptr->a);
return 0;
}

In the above code, we have created a pointer variable, i.e., *ptr, that stores the address of var
variable. Now, ptr can access the variable 'a' by using the (->) operator.

Storage class
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial
value of a variable. There are four types of storage classes in C

o Automatic
o External
o Static
o Register
Storage Storage Default Scope Lifetime
Classes Place Value

Auto RAM Garbage Local Within function


Value

Extern RAM Zero Global Till the end of the main program Maybe
declared anywhere in the program

Static RAM Zero Local Till the end of the main program, Retains
value between multiple functions call

Register Register Garbage Local Within the function


Value

Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are defined.

The scope of the automatic variables is limited to the block in which they are defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.

#include <stdio.h>
int main()
{
int a = 10,i;
printf("%d ",++a);
{
int a = 20;
for (i=0;i<3;i++)
{
printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
}
}
] printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
}

Output:

11 20 20 20 11

Static
o The variables defined as static specifier can hold their value between the multiple
function calls.
o Static local variables are visible only to the function or the block in which they are
defined.
o A same static variable can be declared many times but can be assigned at only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has
declared.The keyword used to define static variable is static.

#include<stdio.h>
static char c;
static int i;
static float f;
static char s[100];
void main ()
{
printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
}
Output
0 0 0.000000 (null)
Register
o The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the
register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU register.
However, it is compiler?s choice whether or not; the variables can be stored in the
register.
o We can store pointers into the register, i.e., a register can store the address of a variable.
o Static variables can not be stored into the register since we can not use more than one
storage specifier for the same variable.

#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register. The initial default
value of a is 0.
printf("%d",a);
}
output
0
External
o The external storage class is used to tell the compiler that the variable defined as extern is
declared with an external linkage elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the external
variable within any block or method.

Example 1
#include <stdio.h>
int main()
{
extern int a; // Compiler will search here for a variable a defined and initialized som
ewhere in the pogram or not.
printf("%d",a);
}
int a = 20; output
20

You might also like