Module-4 CPS(Structures & Pointers)
Module-4 CPS(Structures & Pointers)
• Drawback of arrays: arrays can be used to represent a collection of elements of the same
data type like int, float etc. They cannot be used to hold a collection of different types of
elements.
• Syntax of Structure Definition: structures must be first defined first for their later use. The
syntax for defining a structure is as shown below:
struct structure_name
{
datatype var1;
datatype var2;
-------
};
The keyword struct declares a structure. The structure_name represents the name of the
structure. The structure definition is always terminated with a semicolon.
• Example:
struct student
{
int rollno;
char name[26];
int marks;
};
In the above example, student is the name of the structure. The members of the student structure
are: name, rollno and marks. A structure itself does not occupy any memory in the RAM.
Memory is allocated only when we create variables using the structure.
a) Declaring Structure Variables: A structure variable declaration is similar to the declaration
of variables of any other data types.
• Syntax for Declaring Structure Variables:
struct structurename var1, var2, …., varN
• Example:
#include<stdio.h>
struct student
{
int roll;
char name[26];
int marks;
};
void main()
{
struct student s1;
printf("Enter the students details\n");
scanf("%d %s %d", &s1.roll, s1.name, &s1.marks);
printf("The details of student:\n");
printf(“Roll no=%d\t Name=%s\t Marks=%d\n”, s1.roll, s1.name, s1.marks);
}
• Program to read and print the employee information such as employee id, name &
salary using structures.
#include<stdio.h>
struct employee
{
int eid;
char name[26];
float salary;
};
void main()
{
struct employee e1;
printf("Enter the employee details\n");
scanf("%d %s %f", &e1.eid, e1.name, &e1.salary);
printf("The details of employee:\n");
printf(“Emp id=%d\t Name=%s\t Salary=%f\n”, e1.eid, e1.name, e1.salary);
}
struct student
{
int rollno;
char name[26];
int marks[6];
};
struct student s[100];
In the above example, we are declaring an array ‘s’ with 100 elements of the type student which
is a structure.
• C program to enter the information like name, register number, marks in 6 subjects of
N students into an array of structures, find the average & display grade based on
average for each student.
#include<stdio.h>
struct student
{
int roll;
char name[26];
int marks[6];
};
void main()
{
struct student s[10];
int i, n, sum, j;
float avg;
printf("Enter the number of students\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the details of student: \n");
printf("Enter the roll number\n");
scanf("%d",&s[i].roll);
printf("Enter the Name\n");
scanf(“%s”, s[i].name);
printf("Enter the Marks of each subject\n");
for (j=0;j<6;j++)
{
scanf("%d",&s[i].marks[j]);
}
}
for(i=0;i<n;i++)
{
sum=0, avg=0.0;
for(j=0;j<6;j++)
{
sum=sum+s[i].marks[j];
}
avg=(float)sum/6;
printf("Roll Number: %d, Name: %s, Avg Marks: %f \n", s[i].roll, s[i].name, avg);
if(avg>=80 && avg<=100)
{
printf("The grade is DISTINCTION\n");
}
else if(avg>=60 && avg<=79)
{
printf("The grade is FIRST CLASS\n");
}
else if(avg>=40 && avg<=59)
{
printf("The grade is SECOND CLASS\n");
}
else
{
printf("The grade is FAIL\n");
}
}
struct student
{
struct name
{
char fname[10];
char lname[10];
};
int rollno;
int marks;
};
In the above example, student is the outer structure and the inner structure name consists of two
members: fname and lname.
outer_structure_variable.inner_structure_variable.member_name;
• Example: s1.n1.fname;
• Program to read and print the student information such as reg.no, date of birth, name
& total marks using nested structures for date of birth.
#include<stdio.h>
struct dob
{
int day;
int month;
int year;
};
struct student
{
int roll;
char name[26];
struct dob d;
};
void main()
{
struct student s1;
printf("Enter the Student details:\n");
printf("Enter roll no: ");
scanf("%d",&s1.roll);
printf("Enter DOB: ");
scanf("%d %d %d",&s1.d.day,&s1.d.month,&s1.d.year);
printf("Enter name: ");
scanf("%s",s1.name);
printf("Student Details:\n");
printf("Roll:%d\t DOB:%d/%d/%d\t Name:%s" ,s1.roll, s1.d.day, s1.d.month, s1.d.year,
s1.name);
}
PASSING STRUCTURES TO FUNCTIONS: Functions are the basic building blocks
of a C program. So, it is natural for C language to support passing structures as parameters in
functions.
pointers can be used to access and manipulate data stored in the memory.
• Advantages of Pointers: Pointers are used frequently in C, as they offer a number of
benefits to the programmers. They include the following:
➢ Pointers are more efficient in handling arrays and data tables.
➢ Pointers allow C to support dynamic memory management.
➢ Pointers provide an efficient way for manipulating dynamic data structures such as
structures, linked lists, queues, stacks and trees.
➢ Pointers increase the execution speed and thus reduce the program execution time.
➢ Pointers can be used to return multiple values from a function via function arguments.
➢ Pointers allow passing a function as argument to other functions.
• How a Pointer Works: Whenever we declare a variable in our programs, the system
allocates somewhere in the memory, an appropriate location to hold the value of the variable.
This location will have its own address number. Consider the following example:
The above statement int var creates a location in the memory to hold integer value. That location
will have an address for example assume it is 5000. The statement var = 200 stores the value 200
at the location whose address is 5000. So, in our example, var is the variable name, 200 is the
value stored in var and 5000 is the address of the memory location containing the variable var.
So, we can access the value 200 either by using the variable name var or by using the address of
the memory location which is 5000.’
“The concept of storing memory address in a variable and accessing the value available at that
address is known as a pointer variable.”
a) Declaring Pointer Variables: In C, every variable must be declared for its type. Since
pointer variables contain addresses that belong to a specific data type, they must be declared
as pointers before we use them.
• Syntax for declaring a pointer is as shown below:
datatype *pointer-name;
This tells the compiler three things about the variable pointer-name. They are: The asterisk (*)
tells that the variable pointer-name is a pointer variable, pointer-name needs a memory location
and pointer-name points to a variable of type datatype.
• Example:
• Method-1:
• Method-2:
• Method-3:
c) Dereferencing: Dereferencing a pointer means getting the value that is stored in the
memory location pointed by the pointer. The operator * is used to do this, and is called
the dereferencing operator.
Another name for the dereferencing operator is the indirection operator.
• Example:
int quantity, *p, n;
quantity=179;
p=&quantity;
n=*p;
• We can access every value of x using p++ to move from one element to another
• C program using pointers to compute the sum of given array elements {10,20,30,40,50}.
#include<stdio.h>
void main()
{
int a[5]={10,20,30,40,50};
int *ptr, i, sum=0;
ptr=&a[0]; //even you can use “ptr=a;”
for(i=0; i<5; i++)
{
sum=sum+*ptr;
ptr++;
}
printf("Sum=%d\n",sum);
}
• C program using pointers to compute the sum, mean and standard deviation of all
elements stored in an array of n real numbers.
#include<stdio.h>
#include<math.h>
void main()
{
float a[10],*ptr, mean, std, sum=0,sumstd=0;
int n,i;
printf("Enter the no. of elements\n");
scanf("%d", &n);
printf("Enter the array elements\n");
for(i=0; i<n; i++)
{
scanf("%f",&a[i]);
}
ptr=a;
for(i=0; i<n; i++)
{
sum=sum+*ptr;
ptr++;
}
mean=sum/n;
ptr=a;
for(i=0; i<n; i++)
{
sumstd=sumstd+pow((*ptr-mean),2);
ptr++;
}
std=sqrt(sumstd/n);
printf("Sum=%f\t",sum);
printf("Mean=%f\t",mean);
printf("Standard Deviation=%f\t",std);
}
POINTERS AS FUNCTION ARGUMENTS: When we pass the address of a variable
as an argument the receiving parameter should be pointers. This process of calling a function
using pointers to pass the addresses of variables is known as “Call by reference”.
This method will directly access the memory locations of actual parameters. So the changes
made on the formal parameters effects the values of actual parameters.
char name[100];
But now let us consider a situation where you have no idea about the length of the text you need
to store. Then we can make use of “Dynamic Memory Management” using pointers.
Dynamic Memory Allocation can be defined as a procedure in which the size of a data
structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by C
defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming.
They are:
• free() - “free” method in C is used to dynamically de-allocate the memory. The memory
allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the
free() method is used, whenever the dynamic memory allocation takes place. It helps to
reduce wastage of memory by freeing it.
➢ Syntax: free(ptr);
• C Program to allocate and deallocate memory for integer array using malloc( ) and
free( ) dynamic memory allocation functions.
#include<stdio.h>
void main()
{
int *arr, n;
printf(“enter the number of array elements: \n”);
scanf(“%d”, &n);
arr = (int*)malloc(n*sizeof(int)); //memory allocation using malloc
if(arr == NULL)
{
printf(“Memory allocation failed\n”);
}
else
{
printf(“Enter the array elements:\n”);
for(i=0; i<n; i++)
{
scanf(“%d”, &arr[i]);
}
}
printf(“The array elements are:\n”);
for(i=0; i<n; i++)
{
printf(“%d\t”, arr[i]);
}
free(arr); //De-allocating using Free
}
• C Program to allocate and deallocate memory for floating number array using calloc()
and free() dynamic memory allocation functions.
#include<stdio.h>
void main()
{
float *arr,
int n;
printf(“enter the number of array elements: \n”);
scanf(“%d”, &n);
arr = (float*)calloc(n,sizeof(float)); //memory allocation using calloc()
if(arr == NULL)
{
printf(“Memory allocation failed\n”);
}
else
{
printf(“Enter the array elements:\n”);
for(i=0; i<n; i++)
{
scanf(“%f”, &arr[i]);
}
}
printf(“The array elements are:\n”);
for(i=0; i<n; i++)
{
printf(“%f\t”, arr[i]);
}
free(arr); //De-allocating using free()
}
• C Program to allocate and reallocate memory for integer array using malloc( ) and
realloc( ) and free( ) dynamic memory allocation functions.
#include<stdio.h>
void main()
{
int *arr,i,n,m;
printf("Enter the number of elements: ");
scanf("%d",&n);
arr=(int*)calloc(n,sizeof(float));
if(arr==NULL)
{
printf("Memory allocation failed\n");
}
else
{
printf("Enter the array elements:\n");
for(i=0; i<n; i++)
{
scanf("%d",&arr[i]);
}
printf("Enter additional M elements:\n");
scanf("%d",&m);
arr=(int*)realloc(arr,m);
printf("Enter the additional array elements:\n");
for(i=n; i<m+n; i++)
{
scanf("%d", &arr[i]);
}
}
printf("The array elements are:\n");
for(i=0; i<n+m; i++)
{
printf("%d\t",arr[i]);
}
free(arr);
}