Unit IV Structures
Unit IV Structures
Basics of structures-structure data types, type definition, accessing structures, Structure operations,
Complex structures-nested structures, structures containing arrays, Array of structures, Structures and
Functions, Unions. Pointers: Understanding Computer Memory –Memory Management-Dynamic
memory Allocation-Memory leaks- Introduction to Pointers – declaring Pointer Variables – Pointer
Expressions and Pointer Arithmetic – Null Pointers – Generic Pointers - Passing Arguments to Functions
using Pointer – Pointer and Arrays –Use of pointers in self-referential structures, notion of linked list.
STRUCTURES:
- Structure is a collection of various data types shares a common name.
- It is a user defined data type.
- Each element in a C structure is called member.
Example:
Student: name, roll no, mark, avg
Book: author, title, price, year
Address: door no, street name, place, state, pin
Arrays Structures
It uses index or subscript to access It uses (.) dot operator and ->(pointer) operator to access members of
an arrayelement. structures
Steps :
1. Declaring structure
2. Declaring structure variable
3. Initializing the members of the structure
4. Accessing the members of structure
1. Declaring structure:
Syntax: Example:
{ {
float percentage;
datatype membern; };
};
Keyword struct is used for creating a structure. Note: semicolon }; in the ending line is must.
Syntax: Example:
1
struct tag_name
{ struct student
datatype member1; {
2
NESTED STRUCTURE:
3
A structure with in a structure is called nested structure.
The elements of nested structure are accessed using dot (.) operator.
Syntax:
structure tagname_1 Example:
{ struct Employee
data_type member1; {
data_type member2; char ename[20];
data_type member3; int empid;
.. int salary;
member n; struct date
structure tagname_2 {
{ int day;
data_type member_1; int month;
data_type member_2; int year;
data_type member_3; }doj;
... }emp;
member_n;
} var1;
} var2;
Syntax:
AccessingdayField : emp1.doj.day
4
Program to display employee details using nested structure: Output:
#include <stdio.h>
struct Employee Employee Name : ramya
{
char ename[20];
int empid; Employee ID : 1001
int salary;
struct date Employee Salary : 25000
{
int day; Employee DOJ : 25/9/1988
int month;
int year;
}doj;
}emp;
int main()
{
struct Employee emp={"ramya",1001,25000,{25,9,1988}};
printf("\nEmployee Name : %s",emp.ename); printf("\
nEmployee ID : %d",emp.empid); printf("\
nEmployee Salary : %d",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", emp.doj.day, emp.doj.month, emp.doj.year);
return 0;
}
ARRAY OF STRUCTURES:
5
- Here s is an array of 5 elements where each element is of type struct student.
- We can use s to store 5 structure variables of type struct student.
- To access individual elements we will use subscript notation ([]) and to access the members of each element we will use dot (.)
operator as usual.
s[0].name : refers to the name member of the 0th element of the array.
s[0].roll_no : refers to the roll_no member of the 0th element of the array.
s[0].marks : refers to the marks member of the 0th element of the array.
printf("\n");
printf("Name\tRoll no\tMarks\n");
for(i = 0; i < MAX; i++ )
{
printf("%s\t%d\t%.2f\n",
s[i].name, s[i].roll_no, s[i].marks);
}
6
return 0;
}
Note:
Here, array of size 5 to store information of 5 students.
7
Example:
Displaying book details using pointer to a structure:
#include <stdio.h>
struct book
{
int bookid;
char bookname[50];
char author[30];
float price;
};
int main()
{
struct book b1; // structure variable
declaration struct book *ptr; // pointer
variable declaration ptr=&b1; // pointer variable
initialization printf("enter the bookid\n");
scanf("%d",&ptr->bookid);
printf("enter the book name\
n"); scanf("%s",ptr-
>bookname); printf("enter
author\n"); scanf("%s",&ptr-
8
>author);
9
printf("Enter price");
scanf("%f",&ptr->price);
printf("book details are\n: %d\t %s\t %s\t %f\n\n",ptr->bookid,ptr->bookname,ptr->author,ptr->price);
}
Output:
enter the bookid
1001
enter the book name
python
enter author
Rossum
Enter price 450
book details are
1001 python Rossum 450.000000
Syntax:
Pointer_variable= (type_cast*) malloc(Size_in _bytes)
Example:
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x
Here, 50 represents the total size to be allocated depending upon 16 bit or 32 bit processor. Hence given, sizeof() function irrespective of 2
byte or 4 byte integer
- If it fails to allocate enough space as specified, it returns a NULLpointer.
- malloc () does not initialize the memory allocated during execution. It carries garbage value.
Program (to copy a string to allocated memory using malloc()):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
10
int main()
{
char *ptr;
ptr = (char*)malloc( 20 * sizeof(char) ); // memory is allocated dynamically
if( ptr== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content is : " \"%s\n", ptr);
free(ptr);
return(0);
}
Output:
Dynamically allocated memory content is : good morning
Syntax:
Pointer_variable= (type_cast*) calloc(n, element_size)
Example:
float *y;
y= (float*) calloc(25, sizeof(float));
Note:
This statement allocates contiguous space in memory to store 25 elements each of size of float( i.e, 4 bytes)
11
(iii) realloc():
- realloc() used to change the memory size that is already allocated using malloc() and calloc() functions.
Syntax:
ptr = realloc(ptr, newsize); //ptr is reallocated with size of newsize.
Example:
int *x;
x = (int*)malloc(50 * sizeof(int));
x = (int*)realloc(x,100); //allocated a new memory to variable x
free()
- free() to release the space that are allocated using memory by malloc (), calloc (), realloc () functions .
- It returns the memory to the system.
Syntax:
free(pointer_variable);
Example:
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable
x free(x); //releases the memory allocated to variable x
12
Output:
Dynamically allocated memory content : good morning
Resized memory : can store 100 characters
C Program to generate Salary Slip of employee( Dynamic memory allocation for Structure using pointers):
#include <stdio.h> Output:
#include<stdlib.h> enter the number of employee2
struct employee enter the nameravi
{ Enter Basic Salary (RS): 12000
char name[10];
int basic, da, hra, ta, others; Enter Hra1000
int pf,it,t;
int net_salary; Enter da500
}e[10];
int main() Enter TA500
{
A structure that contains at least one pointers to a structure as its member along with other members is known as self-referential structure.
13
Pointer variable declaration in structure Self-referential structure declaration
struct name { struct name {
member 1; member 1;
member 2; member 2;
... ...
member n; struct name *pointer;
}; };
struct name *pointer;
The above illustrated self referential structure prototype describes one node that comprises of two logical segments.
One segment stores data and the other segment is a pointer indicating where the next element is present.
Several such inter-connected nodes create a chain of structures(Linked List).
14
2. Deleting a node:
If node to be deleted is root, simply delete it.
To delete a middle node, we must have pointer to the node previous to the node to be deleted. So if positions is not zero, we run a loop
position-1 times and get pointer to the previous node.
Advantages of linked list over arrays:
1) list uses Dynamic size whereas, array uses static size.
2) Easy to insert/delete element in list where as array requires shifting of elements.
Drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search
with linked lists.
2) Extra memory space for a pointer is required with each element of the list.
Program to insert, delete and display the elements in singly linked list Output:
15
count++;
break;
case 2:
delet();
count--;
if(count==0)
{
printf("\n List empty\n");
}
break;
case 3:
printf("List elements are:\n");
display();
break;
}
printf("\nEnter your option\n");
}while(opt!=4);
}
void create()
{
if(p==NULL)
{
p=(LIST*)malloc(sizeof(LIST));
printf("Enter the element\n");
scanf("%d",&p->no);
p->next=NULL;
h=p;
}
else
{
t=(LIST*)malloc(sizeof(LIST));
printf("enter the element");
scanf("%d",&t->no);
t->next=NULL;
p->next=t;
p=t;
}
}
void insert()
{
t=h;
p=(LIST*)malloc(sizeof(LIST));
printf("enter the element to be inserted\n");
scanf("%d",&p->no);
printf("enter the position to insert\n");
scanf("%d",&pos);
if(pos==1)
{
h=p;
h->next=t;
}
else
{
for(j=1;j<(pos-1);j++)
t=t->next;
p->next=t->next;
t->next=p;
t=p;
16
17
}
}
void delet()
{
printf("enter the position to delete:\n");
scanf("%d",&pos);
if(pos==1)
{
h=h->next;
}
else
{
t=h;
for(j=1;j<(pos-1);j++)
t=t->next;
pt=t->next->next;
free(t->next);
t->next=pt;
}
}
void display()
{
t=h;
while(t->next!=NULL)
{
printf("\t%d",t->no);
t=t->next;
}
printf("\t %d\t",t->no);
}
TYPEDEF:
- Typedef keyword is used to create a user defined name for existing data type.
- Generally typedef are use to create an alias name (nickname).
Syntax:
typedef datatype alias_name;
typedef int intdata;
18
{
char name[20]; enter the name
int tel_no;
}t1;
anitha
int main()
{
enter the telephone number
t1 t11;
printf("enter the name");
scanf("%s",t11.name); 3216546531
printf("enter the telephone number");
scanf("%s",&t11.tel_no); Name:anitha
printf("Name:%s\n",t11.name);
printf("telephone number is:%d",t11.tel_no); telephone number :909193779
return(0);
}
1. C program to read, display, add, and subtract two distances. Distance must bedefined Output
using kms and meters using structures.(typedef)
Program:
#include <stdio.h> ***MAIN MENU***
typedef struct distance 1. Read the distances
2. Display the distances
{
3. Add the distances
int kms; 4. Subtract the distances
int metres; 5. EXIT
} DISTANCE; // structure variable Enter your option: 1
DISTANCE add_distance (DISTANCE, DISTANCE);
DISTANCE Enter the first distance in kms and metres:
subtract_distance(DISTANCE,DISTANCE); 3
320
DISTANCE dl, d2, d3, d4;
Enter the second distancekms and metres:
int main() 5
{ 100
int option;
do ***MAIN MENU***
{ 1. Read the distances
2. Display the distances
printf("\n ***MAIN MENU***");
3. Add the distances
printf ("\n 1. Read the distances "); 4. Subtract the distances
printf ("\n 2. Display the distances"); 5. EXIT
printf ("\n 3. Add the distances "); Enter your option: 2
printf ("\n 4. Subtract the distances");
printf ("\n 5. EXIT"); The first distance is: 3 kms 320 metres
printf ("\n Enter your option: "); The second distance is: 5 kms 100 metres
***MAIN MENU***
scanf("%d", &option); 1. Read the distances
switch(option) 2. Display the distances
{ 3. Add the distances
case 1: 4. Subtract the distances
printf("\n Enter the first distance in kms and metres: "); 5. EXIT
scanf ("%d %d", &dl .kms, &dl .metres); Enter your option: 3
printf("\n Enter the second distancekms and metres: ");
The sum of two distances is: 8 kms 420 metres
scanf ("%d %d" , &d2 .kms, &d2 .metres); ***MAIN MENU***
break; 1. Read the distances
case 2: 2. Display the distances
printf("\n The first distance is: %d kms %d metres " , dl.kms, dl.metres); printf("\ 3. Add the distances
n The second distance is: %d kms %d metres " , d2 .kms, d2 .metres); 4. Subtract the distances
break; 5. EXIT
Enter your option: 4
case 3:
d3 = add_distance(dl, d2); The difference between two distances is: 1
19
printf("\n The sum of two distances is: %d kms %d metres", d3.kms, d3.metres);
2.C program to add, subtract two complex numbers using structure. Output
Program: Press 1 to add two complex numbers
#include <stdio.h> Press 2 to subtract two complex numbers
#include <stdlib.h> Press 3 to exit
struct complex Enter your choice
{ 1
int real, img; Enter a and b where a + ib is the first complex
}a,b,c; // Structure Variable number.
int main() a=3
{ b=5
Enter c and d where c + id is the second
20
int choice; complex number.
while(1)
{ c=2
printf("Press 1 to add two complex numbers\n"); d=6
printf("Press 2 to subtract two complex numbers\n"); Sum of two complex numbers = 5 + 11i
printf("Press 3 to exit\n"); Press any key to enter choice again...
printf("Enter your choice\n");
scanf("%d",&choice); Press 1 to add two complex numbers
if( choice == 3) Press 2 to subtract two complex numbers
{ Press 3 to exit
exit(0); Enter your choice
} 2
if(choice >= 1 && choice <= 2) Enter a and b where a + ib is the first complex
{ number.
printf("Enter a and b where a + ib is the 1st complex number."); a=1
printf("\na = "); b=1
scanf("%d", &a.real); Enter c and d where c + id is the second
printf("b = "); complex number.
scanf("%d", &a.img); c=2
printf("Enter c and d where c + id is the 2nd complex number."); d=1
printf("\nc = "); Difference of two complex numbers = -1 + 0i
scanf("%d", &b.real); Press any key to enter choice again...
printf("d = "); Press 1 to add two complex numbers
scanf("%d", &b.img); Press 2 to subtract two complex numbers
} Press 3 to exit
if ( choice == 1 ) Enter your choice
{ 3
c.real = a.real + b.real;
c.img = a.img + b.img;
if ( c.img >= 0 )
printf("Sum of two complex numbers = %d + %di", c.real, c.img);
else
printf("Sum of two complex numbers = %d %di",c.real,c.img);
}
else if ( choice == 2 )
{
c.real = a.real - b.real;
c.img = a.img - b.img;
if ( c.img >= 0 )
printf("Difference of two complx no = %d + %di",c.real, c.img);
else
printf("Difference of two complex no = %d %di", c.real, c.img);
}
printf("\nPress any key to enter choice again...\n");
}
}
3. Define a structure called student that would contain name, regno and marks of five
subjects and percentage. Write a C program to read the details of name, regno and marks of five subjects for 30 students and calculate
the percentage and display the name, regno, marks of 30 subjects and percentage of each student.( AssignmentQuestion)
21
Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Example Program: Sorting of names –
Parameter passing: Pass by value, Pass by reference – Example Program: Swapping of two numbers and changing the value of a variable
using pass by reference.
POINTERS:
Apointerisavariablethatholdstheaddressofavariableor afunction.
It is a derived data type in c language.
Onlyaddresscanbeassignedtoapointervariable
Pointer variable is declared with * symbol.
Advantages:
Pointer reduces the code and improves the performance, because it direct access the address of variable.
Pointerscanbeusedtoreturnmultiple valuesfromafunctionviaarguments.
It allowsdynamic memory allocation.
Declarationofavariable:
Pointer_variable=&variable_name; p=&a;
Function Output
printf(“%d”,a); 50
printf(“%u”,&a); 1001
printf(“%u”,p); 1001
printf(“%u”,&p); 2047
printf(“%d”,*p); 50
Pointer Operators:
22
Simply, To create pointer to a variable we use “*” operator and to find the address of variable we use “&” operator. Eg,
23
Note:
All the arithmetic operations can be performed on values. But only subtraction, increment and decrement can be performed on
address.
Addition:
We cannot add two pointers.
This is because pointers contain addresses, adding two addresses makes no sense, because you have no idea what address would
address it would point to. It may go beyond the limit also. Eg, p1+p2
Subtraction:
We can subtract two pointers.
This is because difference between two pointers gives the number of elements of its data type that can be stored between the two
pointers. Eg, p2-p1
Increment:
If the pointer p1 points to an integer whose address is 1000 , after this increment operation, p1 will point to the location 1002
because each time p1 is incremented, it will point to the next integer location which is 2 bytes next to the current location for
integer data type.
If p1 points to a character whose address is 1000, then the above operation will point to the location 1001 because the next
character will be available at 1001. Eg, p1++;
Decrement:
Similarly, depending upon the size of data type, the position is decremented Eg, p1--;
Operators Arithmetic operators on value Arithmetic operators on address
Example
Subtraction(-) *p1-*p2 p2-p1(legal)
5-6=-1 1002-1000=1(2 bytes of data)
24
Program for pointer arithmetic Output:
#include <stdio.h> p1 = 2680014
int main() p2 = 2680012
{ *p1+*p2 = 15
int a = 5, b = 10, c = 0; p1-p2 = 1
int *p1; // pointer declaration p1++ = 2680018
int *p2; p2-- = 26800010
int *p3;
p1 = &a; // pointer initialization
p2 = &b;
printf("p1 = %u\n", p1); //printing the address of a
printf("p2 = %u\n", p2);//printing the address of b
c = *p1+*p2;
printf("*p1+*p2 = %d\n", c);
p3 = p1-p2;
printf("p1 - p2 = %u\n", p3);
p1++;
printf("p1++ = %u\n", p1);
p2--;
printf("p2-- = %u\n", p2);
25
- Pointer to array simply points to base address of an array
- Base address is nothing but starting address ( address of 0th element).
- The address (memory location) of next element is dependent on size of data types( 2 bytes or 4 bytes for integer depending on the
compiler ).
Pointer initialization:
int a[5]={10,20,30,40,50};
int *p;
p=a;
here, pointer variable ‘p’ points only to the base address(starting address) of array.
So, p=a ;
is same as p=&a[0];
26
return 0; To get the value at address use indirection operator (*).
} So *arr[0] gives value at address[0], Similarly *arr[1] gives the
Output: value at address arr[1] and so on.
Address = 37814036 Value = 10
Address = 37814032 Value = 20
Address = 37814028 Value = 30
TYPES OF POINTERS:
NULL pointer:
1. When a null pointer is compared with a pointer to any object the result of comparison is always false.
2. Two null pointers always compares equal.
27
28
3. Dereferencing null pointer leadsto error.
Void pointer:
NULL vs Void Pointer – Null pointer is a value, while void pointer is a type
Declaration:
int **ptr; // declaring double pointers
29
Initialization:
int a= 78;
int *ptr2; // pointer for variable a
int **ptr1; // double pointer for ptr2
ptr2 = &a; // storing address of a in ptr2
ptr1 = &ptr2;
Call by Value:
30
printf("changed value is x=%d \n",num);
}
Actual and formal arguments will be created in different Actual and formal arguments will be created in same memory
memory location location
Slow processing because new address are created. Fast because existing address are used.
Illustrative Program( Swapping of two numbers and changing the value of a variable using pass by value and reference)
Swapping of 2 vaues(Exchanging) using call by reference: Swapping of 2 values(Exchanging) using call by Reference:
31
#include<stdio.h> void swap(int, int); int main()
{
int a=5,b=10;
printf("Before Swap values of a and b is %d %d\n", a, b); swap(a, b);
return(0);
}
32
#include<stdio.h>
void swap(int *x, int*y); int main()
{
int a=5,b=10;
printf("Before Swap values of a and b is %d %d\n", a, b); swap(&a, &b);
printf("After Swap values of a and b is %d %d\n", a, b); return(0);
}
Output:
Before Swap values of a and b is 5 10 After Swap values of a and b is 10 5
33