Unit 4 PC Notes
Unit 4 PC Notes
Structure - Nested structures – Pointer and Structures – Array of structures – Self referential
structures – Dynamic memory allocation - Singly linked list – typedef – Union - Storage classes and
Visibility.
4.1 Introduction
Array is a collection of elements of same type, but many times we have to store the
elements of different data types. The structure is a convenient way of grouping several
pieces of related information together.
Structure is a collection of different types of variables under single name.
4.2 Need for Structure Data Type
A variable stores a single value of a data type.
Arrays can store many values of similar data type.
In real life, we need to store values of different data types.
For Example, To maintain employee’s information we should have information such as their
name,age, qualification, salary etc.
Here, to maintain the information of employees, dissimilar data types are required.
For tackling such mixed data types, a special data type provided by C called structure .
Hence Structure is needed.
4.3 Structure Definition
A structure is a collection of variables of different data types, grouped together under
a single name.
Consider the data of student mark analysis: The data required are name, rollno marks, and
average. A structure data type called student can hold all this information:
struct student
{ char name[20];
int rollno;
int marks[8];
float avg;
};
The following are other examples for structure type
1
4.4.1 Rules for declaring a structure:
A structure definition must end with a semicolon
The structure appears at the top of the source program
The structure variable must be accessed with dot(.) operator
The structure can be declared with the keyword struct following the name and opening
brace with data elements of different type, then closing brace with semicolon.
The individual structure elements are called as members.
Name given to structure is called tag.
Declaration of Structure reserves no space. It is nothing but the “Template / Map / Shape”
of the structure.
Memory for structure variable is created, very first time when the variable is created.
Exampe Program 2 : To print student number, name, and marks using structure
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int rollno;
int eng, phy, mat;
float avg;
}s;
3
void main(){
float total;
clrscr();
printf("Enter student details:\n");
printf("Enter student name:");
scanf("%s", s.name);
printf("Enter student roll no:");
scanf("%d",&s.rollno);
printf("Enter three subject mark:");
scanf("%d %d %d", &s.eng, &s.phy, &s.mat);
total=s.eng+s.phy+s.mat;
s.avg=total/3;
printf("\n Average of %s, Roll No:%d is %0.2f", s.name, s.rollno, s.avg);
getch();
}
Output:
Enter student details:
Enter student name : aaa
Enter student roll no : 1
Enter three subject mark : 90 80 75
Average of aaa, Roll No:1 is 81.67
4.6 Uses of Structure :
Structure allows grouping of different types of data
We can pass structure variable to a function like a normal variable
Complex data types can be handled by using nesting of structures
It is possible to create structure pointers
Structure provides flexibility to programmers to define own data types as per the
requirement
4.7 ARRAY OF STRUCTURES [or] Structure variable as array
A Structure is used to store the information of one particular object but if we need to store
more abjects such as 100 objects, then Array of Structure is used.
Example :
struct Bookinfo
{
char Name[20];
int Pages;
float Price;
}Book[100];
Explanation :
Here Book structure is used to Store the information of one Book.
In case if we need to store the Information of 100 books then Array of Structure isused.
Book[0] stores the Information of 1st Book ,B[1] stores the information of 2nd Bookand So
on We can store the information of 100 books.
Book[3] is shown Below
Name Pages Price
Book [0]
Book [1]
Book [2]
5
Way 1 : Declaration of one structure within another
struct date
{
int date;
int month;
int year;
};
struct Employee
{
char ename[20];
int id;
float salary;
struct date doj;
}emp1;
Output:
Details of student:
Enter name: aaa
Enter age: 19
Enter dob: 12/08/2003
Enter roll no: 101
Enter Total marks: 540
.....
Name: aaa
Age: 19
DOB: 12/08/2003
Roll no: 101
Marks: 540.00
7
// Example Program for pointer to Structure
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[30];
float marks;
};
void main ()
{
struct student s;
struct student *st;
clrscr();
printf("enter sno, sname, total marks:");
scanf ("%d%s%f", &s.sno, s.sname, &s. marks);
st = &s;
printf ("\nDetails of the student are\n");
printf ("Number = %d\n", st ->sno);
printf ("Name = %s\n", st->sname);
printf ("Marks =%f\n", st ->marks);
getch();
}
Output:
enter sno, sname, total marks:101 aaa 700
Details of the student are
Number = 101
Name = aaa
Marks =700.000000
8
Additional Programs based on Structure
1. Program To generate student mark sheets with subject details and the grades using structure
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int rollno;
int m1,m2,m3,tot;
float avg;
}s[30];
void main()
{
int i, n;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter Student %d details",i+1);
printf("\nEnter name:");
scanf("%s",s[i].name);
printf("Enter Rollno:");
scanf("%d",&s[i].rollno);
printf("Enter 3 subject marks:");
scanf("%d%d%d",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].tot=0,s[i].avg=0.0;
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3;
}
printf("\t\t\tSTUDENTS MARK SHEET");
printf("\n\t\t ");
printf("\nName\tRollno\tMark1\tMark2\tMark3\tTotal\tAvg ");
for(i=0;i<n;i++)
printf("\n%s\t%d\t%d\t%d\t%d\t%d\t%f\t%c",s[i].name,s[i].rollno,s[i].m1,s[i].m2,s[i]
} .m3,s[i].tot,s[i].avg);
OUTPUT
Enter number of students: 2
Enter Student 1 details
Enter name: AAA
Enter Rollno: 101
Enter 3 subject marks: 90 89 98
9
2. Program to Print employee details using Structure
#include <stdio.h>
struct Employee
{
char ename[20];
int id;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"ccc",1000,1000.50,{22,6,1990}};
void main()
{
printf("\nEmployee Name: %s",emp.ename);
printf("\nEmployee IDNo: %d",emp.id);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ: %d/%d/%d", emp. doj. date, emp.doj.month, emp.doj.year );
}
Output
Employee Name : ccc
Employee ID 1000
Employee Salary 50000
Employee DOJ : 22/6/1990
3. Program To print the given employee personal details using nested structure
#include<stdio.h>
#include<conio.h>
struct dob
{
int dd;
int mm;
int yy;
}dt;
struct address
{
char st[20];
char city[20];
}add; long int pin;
struct employee
{
int empid;
char name[20];
struct dob dt;
char pan[10];
long int phone;
10
struct address add;
char dept[10];
int exp;
}emp;
void main()
{
clrscr();
printf("Enter the Employee details:\n");
printf("\nEnter name and empid:");
scanf("%s%d",emp.name,&emp.empid);
printf("\nEnter Employee's date of birth:");
scanf("%d%d%d",&emp.dt.dd,&emp.dt.mm,&emp.dt.yy);
printf("\nEnter pan number and phone number:");
scanf("%s%ld",emp.pan,&emp.phone);
printf("Enter Employee's address details");
printf("\nEnter state, city and pin number:");
scanf("%s%s%ld",emp.add.st,emp.add.city,&emp.add.pin);
printf("\nEnter department and year of experience detail:");
scanf("%s%d",emp.dept,&emp.exp);
printf("\n");
printf("The Employee details are:\n");
printf("\nEmployee Name:\t%s",emp.name);printf("\nEmployee Id:\t%d",
emp.empid);
printf("\nEmployee DOB:\t%d\%d\%d",emp.dt.dd,emp.dt.mm,emp.dt.yy);
printf("\nEmployee Pan no:\t%s",emp.pan);
printf("\nEmployee Phone number:\t%ld",emp.phone);
printf("\nEmployee Address:\t%s\t%s\t%ld", emp.add.st, emp.add.city,
emp.add.pin);
printf("\nEmployee Department:\t%s",emp.dept);
printf("\nEmployee Year of Experience:\t%d",emp.exp);
} getch();
OUTPUT
11
4. Program for Salary Slip Generation using structure
#include <stdio.h>
struct employee
{ char name[10];
int basic, da, hra, ta, others;
int pf,it;
int net_salary,gross_salary,deduction;
}e[10];
void main()
{
int i,n;
struct employee *ptr[10];
printf("enter the number of employee");
scanf("%d",&n);
for(i=0;i<n;i++)
{
ptr[i]=&e[i];
printf("enter the name");
scanf("%s",ptr[i]->name);
printf("Enter Basic Salary (RS): ");
scanf("%d",&ptr[i]->basic);
ptr[i]->hra=(ptr[i]->basic*15)/100;
ptr[i]->ta=(ptr[i]->basic*20)/100;
ptr[i]->others=(ptr[i]->basic*10)/100;
//calculate DA 12% of Basic Salary
ptr[i]->da = (ptr[i]->basic*30)/100;
//calculate PF 14% of Basic salary
ptr[i]->pf = (ptr[i]->basic*2)/100;
//calculate IT, 15% of Basic salary
ptr[i]->it = (ptr[i]->basic*2)/100;
//calculate net salary
ptr[i]->gross_salary = ptr[i]->basic + ptr[i]->da + ptr[i]->hra + ptr[i]->ta +
ptr[i]->others;
ptr[i]->deduction=ptr[i]->pf+ptr[i]->it;
ptr[i]->net_salary=ptr[i]->gross_salary-ptr[i]-> deduction;
}
//printing Net salary
for(i=0;i<n;i++)
{
printf("\n Name is %s",ptr[i]->name);
printf("\t Net Salary is:RS %d\n",ptr[i]->net_salary);
}
}
Output
enter the number of employee 2
enter the name aaa
Enter Basic Salary (RS): 100
enter the namebbb
Enter Basic Salary (RS): 200
Name is aaa Net Salary is:RS 171
Name is bbb Net Salary is:RS 342
12
5. Program for Student Database Program
#include<stdio.h>
#include<string.h>
struct student
. {
char name[20];
int roll_no, i;
int marks;
}a[10];
void main()
{
int i,n;
struct student *arr_student[10];
clrscr();
printf("enter the number of Student");
scanf("%d",&n);
printf("enter the Student Details one by one");
for(i=0;i<n;i++)
{
arr_student[i] = &a[i];
printf("\nEnter details of student" );
printf("Enter name: ");
scanf("%s", arr_student[i]->name);
printf("Enter roll no: ");
scanf("%d", &arr_student[i]->roll_no);
printf("Enter marks: ");
scanf("%d", &arr_student[i]->marks);
}
for(i=0;i<n;i++)
{
printf("\n");
printf("Name\tRoll no\tMarks\n");
printf("%s\t%d\t%d\n",arr_student[i]->name, arr_student[i]->roll_no,
arr_student[i]->marks);
}
getch();
}
Output:
enter the number of Student2
enter the Student Details one by one
Enter details of studentEnter name: xxx
Enter roll no: 45
Enter marks: 345
Enter details of studentEnter name: yyy
Enter roll no: 46
Enter marks: 509
Name Roll noMarks
xxx 45 345
13
6. Program for passing structure to function – Student Details
#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
char grade[10];
int roll_no, i;
int marks1,marks2,marks3,percentage;
}s[10];
void internal(struct student s[],int);
void main()
{
int n,i;
clrscr();
printf("\n enter the number of student");
scanf("%d",&n);
printf("\n enter the Details one by one");
for(i=0;i<n;i++)
{
printf("\n Enter name: ");
scanf("%s", s[i].name);
printf("\n Enter roll no: ");
scanf("%d", &s[i].roll_no);
printf("\n Enter marks1: ");
scanf("%d", &s[i].marks1);
printf("\n Enter marks2: ");
scanf("%d", &s[i].marks2);
printf("\n Enter marks3: ");
scanf("%d", &s[i].marks3);
printf("\n Enter Attendance percentage:");
scanf("%d", &s[i].percentage);
}
internal(s,n);
getch();
}
void internal(struct student s[],int n)
{
int i;
float inter[10],atten[10];
for(i=0;i<n;i++)
{
if(s[i].percentage>95)atten[i]=5;
else
if(s[i].percentage>90)atten[i]=4;
else
if(s[i].percentage>85)atten[i]=3;
else
if(s[i].percentage>80)atten[i]=2;
else
if(s[i].percentage>75)atten[i]=1;
else
14
atten[i]=0;
inter[i]=(((s[i].marks1/100)*5)+((s[i].marks2/100)*5)+((s[i].marks3/100)*5)+
atten[i]);
printf("\n The student name is %s,\t internal mark is %f", s[i].name,
inter[i]);
}
}
OUTPUT
enter the number of student1
enter the Details one by one
Enter name: aaa
Enter roll no: 1
Enter marks1: 100
Enter marks2: 100
Enter marks3: 90
Enter Attendance percentage:100
The student name is aaa, internal mark is 15.000000
malloc() function in C:
malloc () function is used to allocate space in memory during the execution of the program.
malloc () does not initialize the memory allocated during execution. It carries garbage value.
malloc () function returns null pointer if it couldn‟t able to allocate requested amount of
memory.
15
}
else
{
strcpy( mem_alloc,"Hello World");
}
printf("Dynamically allocated memory content : %s \n", mem_alloc );
free(mem_alloc);
}
OUTPUT
Dynamically allocated memory content: Hello World
calloc() function in C:
calloc () function is also is used to allocate space in memory during the execution of the
program like malloc () function. But calloc () initializes the allocated memory to zero.
Example Program for calloc() function in C:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, n;
int *a;
printf("Number of elements to be entered:");
scanf("%d",&n);
a = (int*)calloc(n, sizeof(int));
printf("Enter %d numbers:\n",n);
for( i=0 ; i < n ; i++ )
scanf("%d",&a[i]);
printf("The numbers entered are: ");
for( i=0 ; i < n ; i++ )
printf("%d ",a[i]);
free( a );
} return(0);
OUTPUT
Number of elements to be entered:5
Enter 5 numbers:
10 20 30 40 50
The numbers entered are: 10 20 30 40 50
realloc () function in C:
realloc () function modifies the allocated memory size by malloc () and calloc () functions to
new size.
If enough space doesn’t exist in memory of current block to extend, new block is
allocated for the fullsize of reallocation, then copies the existing data to new block and then
frees the old block.
free() function in C:
free () function frees the allocated memory by malloc (), calloc (), realloc () functions and
returns thememory to the system.
16
Example Program for realloc() and free() functions in C:
#include<stdio.h>
void main()
{
char *p;
p=(char*)malloc(7);
strcpy(p," CHENNAI ");
printf("memory contains %s",p);
p=(char*)realloc(p,10);
strcpy(p,"VIJAYAWADA");
printf("\n memory now contains %s",p);
free(p);
}
OUTPUT
memory contains CHENNAI
memory now contains VIJAYAWADA
Example :
struct node
{
int data;
struct node *next;
};
The following figure depicts the composition of such a node. The figure is a simplified
illustration of nodes that collectively form a chain of structures or linked list.
17
Example Program
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*start=NULL;
void main()
{
char ch;
struct node *current, *new_node;
do
{
new_node=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the data to create : ");
scanf("%d",&new_node->data);
new_node->next=NULL;
if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{ current->next=new_node;
current=new_node;
}
printf("\nDo you want to create another: ");
ch=getche();
} while(ch!='n');
current=start;
printf("\n the linked list is");
do
{
printf("%d ->",current->data);
current=current->next;
}
while(current!=NULL);
printf(" NULL");
}
OUTPUT
18
4.13 Linked List
Linked List i s a l i n e a r collection of data elements called nodes. These nodes are
randomly stored in the memory.
Node Structure: A node in a linked list typically consists of two
components: Data: It holds the actual value or data associated with
the node. Next Pointer: It stores the memory address of the next node in the sequence.
Head and Tail: The linked list is accessed through the head node, which points to the first
node in the list. The last node in the list points to NULL or nullptr, indicating the end of the
list. This node is known as the tail node.
Types of linked lists: There are mainly three types of linked lists:
1. Single-linked list
2. Double linked list
3. Circular linked list
19
Node Creation
struct node
{
int data;
struct node *next;
};
struct node *head, *ptr;
ptr = (struct node *)malloc(sizeof(struct node *));
20
3. To insert a node at the end of a Linked List, we need to:
Go to the last node of the Linked List
Change the next pointer of last node from NULL to the new node
Make the next pointer of new node as NULL to show the end of Linked List
We have to properly deallocate any memory used by the deleted node to avoid memory leaks.
21
//Program for insertion, deletion , display operations on linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;
void beginsert();
void begin_delete();
void display();
void main()
{
beginsert();
beginsert();
beginsert();
display();
begin_delete();
display();
}
void beginsert()
{
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nList is empty\n");
}
else
{
22
ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining ...\n");
}
}
void display()
{
struct node *ptr;
ptr = head;
if(ptr == NULL)
{
printf("Nothing to print");
}
else
{
printf("\n printing values in list \n");
while (ptr!=NULL)
{
printf("\n%d",ptr->data);
ptr = ptr -> next;
}
}
}
Output :
Enter value
10
Node inserted
Enter value
20
Node inserted
Enter value
30
Node inserted
printing values in list
30
20
10
Node deleted from the begining ...
23
// Example Program2 for all operations on linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;
void beginsert();
void lastinsert();
void randominsert();
void begin_delete();
void last_delete();
void random_delete();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n\n*********Main Menu*********\n");
printf("\n Choose one option from the following list ...\n");
printf("\n===============================\n");
printf("\n 1.Insert in beginning \n
2. Insert at last \n
3. Insert at any random location \n
4.Delete from Beginning \n
5.Delete from last \n
6.Delete node after specified location \n
7.Search for an element \n
8.Show \n
9.Exit \n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
beginsert();
break;
case 2:
lastinsert();
break;
case 3:
randominsert();
break;
case 4:
begin_delete();
break;
24
case 5:
last_delete();
break;
case 6:
random_delete();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void beginsert()
{
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
25
{
printf("\nEnter value?\n");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
ptr -> next = NULL;
head = ptr;
} printf("\nNode inserted");
else
{
temp = head;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp->next = ptr;
ptr->next = NULL;
printf("\nNode inserted");
}
}
}
void randominsert()
{
int i,loc,item;
struct node *ptr, *temp;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{ printf("\n Enter element value");
scanf("%d",&item);
ptr->data = item;
printf("\n Enter the location after which you want to insert ");
scanf("\n%d",&loc);
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\ncan't insert\n");
return;
}
}
ptr ->next = temp ->next;
temp ->next = ptr;
26
printf("\nNode inserted");
}
}
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nList is empty\n");
}
else
{ ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining ...\n");
}
}
void last_delete()
{
struct node *ptr,*ptr1;
if(head == NULL)
{
printf("\nlist is empty");
}
else if(head -> next == NULL)
{
head = NULL;
free(head);
} printf("\nOnly node of the list deleted ...\n");
else
{
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL;
free(ptr);
printf("\nDeleted Node from the last ...\n");
}
}
void random_delete()
{
struct node *ptr,*ptr1;
int loc,i;
printf("\n Enter the location of the node after which you want to perform deletion
27
\n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc;i++)
{
ptr1 = ptr;
ptr = ptr->next;
if(ptr == NULL)
{
printf("\nCan't delete");
return;
}
}
ptr1 ->next = ptr ->next;
free(ptr);
printf("\nDeleted node %d ",loc+1);
}
void search()
{
struct node *ptr;
int item, i=0, flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{ printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("item found at location %d", i+1);
flag=0;
}
else
{ flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("Item not found\n");
}
}
}
void display()
28
{
struct node *ptr;
ptr = head;
if(ptr == NULL)
{
printf("Nothing to print");
}
else
{ printf("\n printing values \n");
while (ptr!=NULL)
{
printf("\n%d",ptr->data);
ptr = ptr -> next;
}
}
}
Output:
29
*********Main Menu********* *********Main Menu*********
Choose one option from the following list Choose one option from the following list
============================= =============================
1. Insert in beginning 1. Insert in beginning
2. Insert at last 2. Insert at last
3. Insert at any random location 3. Insert at any random location
4. Delete from Beginning 4. Delete from Beginning
5. Delete from last 5. Delete from last
6. Delete node after specified location 6. Delete node after specified location
7. Search for an element 7. Search for an element
8. Show 8. Show
9. Exit 9. Exit
30
*********Main Menu********* *********Main Menu*********
Choose one option from the following list Choose one option from the following list
============================= =============================
1. Insert in beginning 1. Insert in beginning
2. Insert at last 2. Insert at last
3. Insert at any random location 3. Insert at any random location
4. Delete from Beginning 4. Delete from Beginning
5. Delete from last 5. Delete from last
6. Delete node after specified location 6. Delete node after specified location
7. Search for an element 7. Search for an element
8. Show 8. Show
9. Exit 9. Exit
Enter your choice?7
Enter item which you want to Enter your choice?9
search?1 item found at location
1
item found at location 2
31
4.15 typedef:
typedef is used to assign alternative names for existing data types. It is used for syntactic
convenience of the user only.
Syntax:
typedef <Existing_data_type> <user defined datatype>;
Example : typedef int number
It is mostly used with user defined datatypes such as structures as the name of the data type
becomes slightly complicated to use in the programs
Example :
typedef struct student
{
char name[50];
int roll;
float marks;
}student_list;
Here stu represents the structure definition associated with it. So it can be used to declare the
variable for this structure as in below statement
Student_list s1,s2;
Example Program
#include <stdio.h>
typedef struct student
{
char name[50];
int roll;
float marks;
}stu;
void main()
{
stu s;
printf("Enter information of students:\n");
printf("\nEnter roll number:");
scanf("%d",&s.roll);
printf("Enter name: "); Output :
scanf("%s",s.name); Enter information of students:
printf("Enter marks: ");
scanf("%f",&s.marks); Enter roll number:1
printf("\n"); Enter name: aaa
Enter marks: 490
printf("Displaying Information:\n");
Displaying Information:
// displaying information
printf("\nRoll number: %d\n",s.roll); Roll number: 1
printf("Name: "); Name: aaa
puts(s.name); Marks: 490.0
printf("Marks: %.1f",s.marks);
printf("\n");
}
32
4.16 Union:
Union is a collection of different types of variables under single name.
Union and structure in C are same in concepts, except allocating memory for their members.
Structure allocates storage space for all its members separately.
Whereas, Union allocates one common storage space for all its members
We can access only one member of union at a time. We can’t access all member values at
the sametime in union. But, structure can access all member values at the same time.
Many union variables can be created in a program and memory will be allocated for each
unionvariable separately.
Below table will help you how to form a C union, declare a union, initializing and accessing
themembers of the union.
33
Example Program For Union:
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
void main()
{
union student record1;
union student record2;
clrscr();
/* assigning values to record1 union variable */
strcpy(record1.name, "AAAA");
strcpy(record1.subject, "Maths");
record1.percentage = 97.50;
printf("Union record1 values example\n");
printf("Name : %s \n", record1.name);
printf("Subject : %s \n", record1.subject);
printf("Percentage : %f \n\n", record1.percentage);
/* assigning values to record2 union variable */
printf("Union record2 values example\n");
strcpy(record2.name, "BBBB");
printf("Name : %s \n", record2.name);
strcpy(record2.subject, "Programming in C");
printf("Subject : %s \n", record2.subject);
record2.percentage = 99.50;
printf("Percentage : %f \n", record2.percentage);
getch();
}
OUTPUT:
Union record1 values example
Name :
Subject :
Percentage : 97.500000
Explanation : The values of record1 is not fully printed because Union allocates one common
storage space for all its members. Hence the percentage which is stored lastly gets printed. In case
of record2, the display of values is done immediately after assigning the values. So all the values are
displayed
34
4.17 Comparison (or Difference) between Structure and Union:
3 We can access more than one member of We can access only one member of union at a
stucture at a time time
4 The size of the structure is equal to the The size is equal to the size of the largest
sum of the size of members member
structure
5 Altering the value of any member willnot Altering the value of any member will affect
affect other members of the other members of the structure
structure
6 Syntax: Syntax:
struct <tag name> union <tag-name>
{datatype member1; {datatype member1;
datatype member2; datatype member2;
……. …….
…… ……
datatype member n ; datatype member n ;
}; };
4.18 Storage classes and Visibility
malloc( ) is a function that creates one calloc( ) is a function that assigns a specified
1. block of memory of a fixed size. number of blocks of memory
4. malloc( ) has high time efficiency calloc( ) has low time efficiency
35
UNIT – IV - PART - A
1. What is structure? Write the syntax for structure.
2. What is meant by structure definition?
3. Write the various operations structure.
4. How the members of structure object is accessed?
5. Write the use of size operator on structure.
6. What is a nested structure?
7. How typedef is used in structure?
8. Interpret the term Union in C.
9. What is mean by Self referential structures?
10. What is the need for typedef?
11. In language C can we allocate memory dynamically? How?
12. Point out the meaning of Dynamic memory allocation.
13. Mention any two application linked list.
14. Generalize the operators used in access the structure members.
15. State the meaning of the root word struct.
16. Show the difference between Structures from Array.
17. Show a structure called ID_Card to hold the details of a student.
18. Summarize the different types of memory allocation functions.
19. Discriminate between malloc and calloc.
20. If we have structure B nested inside structure A, when do we declare structure B?
21. How to create a node in singly liked list?
22. Compare and contrast Structure with Union
23. Write the syntax for pointers to structure.
What is the output of the following code fragment?
struct point
{
int x, y;
};
24. struct point origin, *pp;
main ()
{
pp = & origin;
printf (" origin is (%d%d)\n", (*pp).x,pp →y);
}
25. Discover the meaning of Array of structure.
36
PART – B
1. Discuss about various storage classes and its visibility
2. Explain about the structures and its operations.
3. Why is singly linked list called as self-referential structure? Explain.
4. Demonstrate about pointers to structures, array of structures and nested structures.
5. Write a C program using structures to prepare the students mark statement.
6. Write a C program using structures to prepare the employee pay roll of a company.
7. Write a C program to read the details of book name, author name and price of 200
books in a library and display the total cost of the books.
What is a structure? Express a structure with data members of various types and
8. declare two structure variables. Write a program to read data into these and printthe same.
37