unit 4
unit 4
IV UNIT- STRUCTURES ➢ For example, if we have to define a structure for a student, then its
related information probably would be: roll_number, name, course,
Structure - Nested structures – Pointer and Structures – Array of and fees.
structures – Example Program using structures and pointers –
➢ This structure can be declared as:
Self- referential structures – Dynamic memory allocation - Singly
linked list - typedef Eg:
struct student
4.1 INTRODUCTION {
int r_no;
➢ A structure is similar to records. char name[20];
➢ It stores related information about an entity. char course[20];
➢ A structure is a user-defined data type that can store related
float fees;
information (even of different data types) together.
};
➢ The major difference between a structure and an array is that,
➢ Now, the structure has become a user-defined data type.
an array contains related information of the same data type.
➢ Each variable name declared within a structure is called a member
➢ A structure is, therefore, a collection of variables under a single
of the structure.
name.
➢ The structure declaration however, does not allocate any memory
➢ The variables within a structure are of different data types and
or consume storage space.
each has a name that is used to select it from the structure.
➢ Like any data type, memory is allocated for the structure when we
declare a variable of the structure.
4.1.1 Structure Declaration
➢ For example, we can define a variable student by writing
➢ A structure is declared using the keyword struct followed by a
structure name. struct student stud1;
➢ All the variables of the structure are declared within the structure. Here, struct student is a data type and stud1 is a variable.
➢ A structure type is generally declared by using the following syntax: Eg:
struct struct-name struct student
{ {
data_type var-name; int roll_no;
data_type var-name; char name[20];
……………….. char course[20];
}; float fees;
1
CS8251-PROGRAMMING IN C
2
CS8251-PROGRAMMING IN C
OR scanf(“%d”,&stud1.r_no);
by writing scanf(“%s”,stud1.name);
struct student studl = {01,"Rahul","BCA",45000};
➢ To print the values of structure variable studl, we may write
printf("%s", studl.course);
printf("%f", studl.fees);
{ DOB = 25-09-1991
int roll_no;
char name[80]; Eg:// Largest of 3 nos
float fees; #include <stdio.h>
char DOB[80]; #include <conio.h>
}; int main()
struct student stud1; {
clrscr (); struct numbers
printf ("\n Enter the roll number: "); {
scanf("%d",&stud1.roll_no); int a, b, c;
printf ("\n Enter the name: "); int largest;
scanf("%s",stud1.name); };
printf ("\n Enter the fees: "); struct numbers num;
scanf ("%f",&stud1.fees); clrscr ();
printf ("\n Enter the DOB:"); printf ("\n Enter the three numbers: ");
scanf("%s", stud1.DOB); scanf("%d %d %d", &num.a, &num.b, &num.c);
printf("\n ********STUDENT'S DETAILS*******"); if(num.a > num.b && num.a > num.c)
printf("\n ROLL No. = %d",stud1.roll_no); num.largest = num.a;
printf("\n NAME = %s",stud1.name); if(num.b > num.a && num.b > num.c)
printf("\n FEES = %f",stud1.fees); num.largest = num.b;
printf ("\n DOB = %s",stud1.DOB); if(num.c > num.a && num.c > num.b)
getch(); num.largest = num.c;
return 0; printf ("\n The largest number is: %d", num.largest);
} getch( );
Output return0;
Enter the roll number: 01 }
Enter the name: Rahul
Enter the fees: 45000 Output
Enter the DOB: 25-09-1991 Enter the three numbers: 7 9 1
********STUDENT'S DETAILS ******* The largest number is: 9
ROLL No= 01
NAME=Rahul
FEES=45000.00
4
CS8251-PROGRAMMING IN C
5
CS8251-PROGRAMMING IN C
printf("\n The sum of two complex numbers is: %d+%di", Eg://Enter two points and then calculate the distance between
sum_c.real,sum_c.imag); them.
break; #include <stdio.h>
case 4: #include <conio.h>
sub_c.real = c1.real - c2.real; #include<math.h>
sub_c.imag = c1.imag - c2.imag; int main()
printf ("\n The difference between two complex numbers is: %d+ %di", typedef struct point
sub_c.real,sub_c.imag); {
break; int x, y;
} }POINT;
}while(option != 5); POINT p1, p2;
getch(); float distance;
return 0; clrscr ();
} printf("\n Enter the coordinates of thefirst point: ");
Output scanf ("%d %d", &p1.x , &p1.y);
1. Read the complex numbers printf("\n Enter the coordinates of the second point: " );
2. Display the complex numbers scanf ("%d %d", &p2.x, &p2.y);
3. Add the complex numbers distance = sqrt (pow( (p1.x - p2 .x) , 2) +pow( (p1.y - p2.y), 2) );
4. Subtract the complex numbers printf (" \n The coordinates of the first point are: %dx %dy”, p1.x,
5. EXIT pl. y);
Enter your option: 1 printf ("\n The coordinates of the second point are: %dx %dy",
Enter the real and imaginary parts of the p2.x, p2.y);
first complex number: 2 3 printf("\n Distance between p1 and p2%f",distance);
Enter the real and imaginary parts of the getch();
second complex number: 4 5 return 0;
******** MAINMENU********* }
1. Read the complex numbers Output
2. Display the complex numbers Enter the coordinates of the first point: 2 3
3. Add the complex numbers Enter the coordinates of the second point: 9 9
4. Subtract the complex numbers The coordinates of the first point are: 2x 3y
5. EXIT The coordinates of the second point are: 9x 9y
Enter your option: 3 Distance between p1 and p2 = 9.219544
The sum of two complex numbers is: 6 + 8i
6
CS8251-PROGRAMMING IN C
7
CS8251-PROGRAMMING IN C
8
CS8251-PROGRAMMING IN C
9
CS8251-PROGRAMMING IN C
10
CS8251-PROGRAMMING IN C
FEES = 60000.00
Eg: // Get the inch details from the user and calculate the distance
Eg:// student details using assignment statement using the structures
printf ("\n DETAILS OF STUDENT"); printf( “ enter the information for second distance”);
printf("\n ROLL NUMBER = %d", ptr_studl->r_no); printf(“ enter the feet ”);
printf ("\n NAME = %s ". ptr_studl ->name) ; scanf(“%d”,&d2.feet);
printf("\n COURSE = %s", ptr_studl->course); printf(“ enter the inch ”);
printf("\n FEES = %f", ptr_studl-> fees); scanf(“%f”,&d2.inch);
return 0; sum.feet=d1.feet+d2.feet;
} sum.inch=d1.inch+d2.inch;
Output // If inch >12, change it to feet
DETAILS OF STUDENT
ROLL NUMBER = 01 if(sum.inch>12.0)
NAME = Rahul {
COURSE = BCA sum.inch=sum.inch-12.0;
FEES = 45000.00 ++sum.feet;
11
CS8251-PROGRAMMING IN C
}
printf(“ sum of distances = %d - %lf ”,sum.feet,sum.inch); 4.7 DYNAMIC MEMORY ALLOCATION
return 0;
} ➢ The process of allocating memory to the variables during
Output: execution of the program or at run time is known as dynamic
Enter the information for first distance memory allocation.
Enter feet: 23 ➢ Till now whenever we needed an array we had declared a static
Enter inch : 8.6 array of fixed size, say int arr[100] ;
➢ When this statement is executed, consecutive space for100 integers
Enter the information for second distance is allocated.
Enter feet: 34 ➢ It is not uncommon that we may be using only 10% or 20% of the
Enter inch : 2.4 allocated space there by wasting rest of the space.
Sum=57-11.0 ➢ To overcome this problem and to utilize the memory efficiently c
language provides a mechanism of dynamically allocating memory
4.6 SELF-REFERENTIAL STRUCTURES so that only the amount of memory that is actually required is
➢ A structure that includes at least one member which is a pointer to reserved.
the same structure type. ➢ We reserve space only at the run time for the variables that are
Syntax: actually required.
struct struct_name
{
member 1;
member 2;
………….
member n;
struct struct_name*name;
};
Eg:
struct student_node
{
int roll_no;
char name[20]; ➢ When we have to dynamically allocate memory for variables in
struct student_node *next; our programs then pointers are the only way to go.
};
12
CS8251-PROGRAMMING IN C
13
CS8251-PROGRAMMING IN C
14
CS8251-PROGRAMMING IN C
➢ In both the situations we can always use realloc() to change the if(str==NULL)
memory size already allocated by calloc() and malloc().This process {
is called reallocation of memory. printf (" \n Memory could not be allocated") ;
➢ The general syntax for realloc() can be given as exit(l) ;
➢ ptr = realloc(ptr,newsize); }
➢ The function realloc() allocates new memory space of size specified strcpy(str,"Hi");
by newsize to the pointer variable ptr. printf("\n STR = %s", str);
➢ It returns a pointer to the first byte of the memory block. str=(char *)realloc(str,20);
➢ The allocated new block may be or may not be at the same region. if(str==NULL)
Thus, we see that realloc() takes two arguments. {
➢ The first is the pointer referencing the memory and the second is the printf("\n Memory could not be reallocated") ;
total number of bytes you want to reallocate. exit(1) ;
➢ If you pass zero as the second argument, itwill be equivalent to }
calling free (). printf("\n STR size modified.\n");
➢ Like malloc() and calloc(),realloc returns a void pointer if printf ("\n STR = %s\n", str);
successful, else a NULL pointer is returned. strcpy(str,"Hi there");
➢ If realloc() was able to make the old block of memory bigger, it printf("\n STR = %s", str);
returns the same pointer. free(str) ;
➢ Otherwise, if realloc() has to go elsewhere to get enough contiguous return 0;
memory then it returns a pointer to the new memory, after copying }
your old data there.
➢ However, if realloc() can't find enough memory to satisfy the new free() (Releasing the used space)
request at all, it returns a null pointer. So again you must check ➢ When a variable allocated space during the compile time, then the
before using, that the pointer returned by the realloc() is not a null memory used by that variable is automatically released by the
pointer. system in accordance with its storage class.
➢ But when we dynamically allocate memory then it is our
Eg: responsibility to release the space when it is not required.
#include< stdio. h>· ➢ Therefore, if we no longer need the data stored in a particular block
#include< stdlib.h> of memory and we do not intend to use that block for storing any
#define NULL 0 other information, then as a good programming practice we must
main() release that block of memory for future use, using the free function.
char *str; ➢ The general syntax of the free() is, free(ptr) ;where ptr is a pointer
str=(char *)malloc(10); that has been created by using malloc() or calloc().
15
CS8251-PROGRAMMING IN C
16
CS8251-PROGRAMMING IN C
17
CS8251-PROGRAMMING IN C
➢ The end of the list is marked by storing NULL or -1 in the NEXT Case 3 The node after the given node is deleted.
field of the last node. When we delete a node from the linked list, we have to free the
➢ For traversing the linked list, we also make use of another pointer memory occupied by that node.
variable PTR which points to the node that is currently being
accessed. Eg:\\ Delete first, middle and last node
18
CS8251-PROGRAMMING IN C
p->next=q->next;
q->next=NULL;
free(q);
}
void display()
{
struct node*temp;
temp=root;
if(temp==NULL)
{
printf(“ No nodes in the list “);
}
else
{
while(temp!=NULL)
{
printf(“%d”,temp->data);
temp=temp->next;
}
}
19