Structures and Union
Structures and Union
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
#include<stdio.h>struct point
int x,y;
};
void main()
Output:
{ (2,3)
%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
Fig. illustrates how the values will be assigned to individual fields of the structure
Example:
stud1.rno=01; stud1.name=”Rahul”;stud1.course=”BCA”;stud1.fees=45000;
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:
Example 2:
int rno;
char name[20]; char course[20];float fees;
};
Copy
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.
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................
}*ptr;
Or
#include <conio.h>
struct student
{
int r_no; Output
char name[20]; Enter the details of the
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
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.
Declaration of node:
struct node
{
int data;
struct node *next;
}
START
.
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;
}
Programming Example
Declare a structure to store information of a particular date.
struct date
{
int day;
int month;
int year;
};
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;
};
int main()
int i, n;
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
scanf("%d", &ptr–>fees);
display(ptr);
getch();
return
}
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 −
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( ) {
return 0;
}
When the above code is compiled and executed, it produces the following result −
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( ) {
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
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
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
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