Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Module-4 CPS(Structures & Pointers)

Module 4 covers structures and pointers in C programming, explaining how structures can hold heterogeneous data types and how to define, declare, and access them. It also discusses pointers, their advantages, and how to use them with arrays and functions, including passing structures as parameters. Additionally, it includes examples of nested structures and various programs demonstrating the use of structures and pointers.

Uploaded by

suprithnj517
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Module-4 CPS(Structures & Pointers)

Module 4 covers structures and pointers in C programming, explaining how structures can hold heterogeneous data types and how to define, declare, and access them. It also discusses pointers, their advantages, and how to use them with arrays and functions, including passing structures as parameters. Additionally, it includes examples of nested structures and various programs demonstrating the use of structures and pointers.

Uploaded by

suprithnj517
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Module – 4: Structures & Pointers

STRUCTURES: “A structure is a collection of heterogeneous data elements referred by


the same name”.

• 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:

struct student s1, s2, s3;

We can use the keyword typedef to define a structure as follows:


typedef struct
{
int rollno;
char name[26];
int marks;
}student;
The name student represents the structure definition associated with it and therefore can be used
to declare structure variables as shown below:
student s1, s2, s3;
b) Accessing Structure Members: We can access and assign values to the members of a
structure in a number of ways. They should be linked to the structure variables in order to
make them meaningful members.
The link between a member and a variable is established using the member operator ‘.’ which
is also known as dot operator or period operator.
• Syntax for accessing a structure member:
structure-varaible.membername
• Example:
s1.name
s1.rollno

c) Structure Initialization: The values can be initialized in two ways


1) static initialization
2) dynamic initialization

• Example for static initialization:


struct student
{
int rollno;
char name[26];
int marks;
};
struct student s1 = {“01”, “nithin”,”96”};
struct student s2 = {“02”,”gowda”,”56”};
• Example for dynamic initialization:
scanf(“%d”, &s1.rollno);
scanf(“%s”, s1.name);
scanf(“%d”, s1.marks);
• Program to read and print the student information such as reg.no, name & marks using
structures.

#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);
}

ARRAYS OF STRUCTURES: If we want to store details of 100 students it will become


difficult to declare and maintain 100 variables and store the data. Instead, we can declare and
array of structure variables as shown below:

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");
}
}

NESTED STRUCTURES: In C, structures can be nested. A structure can be defined


within in another structure.

• Example of nested structure:

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.

• The members of the inner structure can be accessed as shown below:

outer_structure_variable.inner_structure_variable.member_name;

• Example: s1.n1.fname;

Where s1 is structure variable of student and n1 is a structure variable of name

• 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.

We can pass the C structures to functions in 3 ways:


1) Passing each individual item of the structure as a function argument.
2) Passing the whole structure as a value.
3) Passing the address of the structure (pass by reference).
Syntax for passing the structure variable as a parameter is shown below:
return-type function-name(struct structname var)
{
----
----
return expression;
}
1] PASSING EACH INDIVIDUAL ITEM OF THE STRUCTURE AS A FUNCTION
ARGUMENT: the structure data members will be passed to another function by value. It means
the whole structure is not passed, instead of that data members and their values will be passed as
arguemnets. So, this structure can be accessed from called function.
Example for pass individual item as a value:
#include <stdio.h>
struct student
{
int roll;
char name[26];
int marks;
};
struct student s1={01,"Nithin",100};
void display(int,char[],int);
void main()
{
display(s1.roll,s1.name,s1.marks);
}
void display(int roll,char name[],int marks)
{
printf("%d\t",s1.roll);
printf("%s\t",s1.name);
printf("%d\t",s1.marks);
}
2] PASSING ENTIRE STRUCTURE TO FUNCTION AS A VALUE: the whole structure is
passed to another function by value. It means the whole structure is passed to another function
with all members and their values. So, this structure can be accessed from called function.
Example for passing entire structure as a value:
#include <stdio.h>
struct student
{
int roll;
char name[26];
int marks;
};
void display(struct student s1);
void main()
{
struct student s1={01,"Nithin",100};
display(s1);
}
void display(struct student s1)
{
printf("%d\t",s1.roll);
printf("%s\t",s1.name);
printf("%d\t",s1.marks);
}
3] PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS: the whole structure is
passed to another function by address. It means only the address of the structure is passed to
another function. The whole structure is not passed to another function with all members.
Example for passing a structure by Address(reference)::
#include <stdio.h>
struct student
{
int roll;
char name[26];
int marks;
};
void display(struct student *);
void main()
{
struct student s1={01,"Nithin",100};
display(&s1);
}
void display(struct student *s1)
{
printf("%d\t",s1->roll);
printf("%s\t",s1->name);
printf("%d\t",s1->marks);
}
POINTERS: A pointer is a derived data type in C. It is built from one of the fundamental data
types available in C. Pointers contain memory addresses as their values. Since these memory
addresses are the locations in the computer memory where program instructions and data are
stored.

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:

int *p; float *p; char *ch;

b) Initialization of pointer variables: The process of assigning the address of a variable


to pointer variable is known as initialization.

• Method-1:

int x; //declare a data variable

int *px; //declare a pointer variable

px=&x // copy the address of data variable to pointer variable

• Method-2:

int x; //declare a data variable

int *px=&x; //assign the address of data variable to pointer variable

• Method-3:

int x,*px=&x; //declare data variable and assign address

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;

POINTERS IN ARRAYS: Consider an 1D-Array


x[5] = {100,101,102,103,104}
• If we declare ptr as an integer pointer, then we can make the pointer ptr to point to the array
x by the following assignment:

ptr=x; this is equivalent to ptr=&x[0];

• 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.

• C Program to Swap two numbers using pointers (call by reference) as Parameters to a


function:
#include<stdio.h>
void swap(int *, int *);
void main()
{
int a, b, *p1, *p2;
printf(“enter two numbers:\n”);
scanf(“%d %d”, &a, &b);
p1=&a; p2=&b;
swap(p1,p2);
}
void swap(int *p1, int *p2) // called function
{
int temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
printf(“Swapped numbers are %d and %d”,*p1,*p2);
}
• C Program to add two numbers using pointers (call by reference) as Parameters to a
function:
#include<stdio.h>
void add(int *, int *);
void main()
{
int a, b, *p1, *p2;
printf(“enter two numbers:\n”);
scanf(“%d %d”, &a, &b);
p1=&a; p2=&b;
add(p1,p2);
}
void add(int *p1, int *p2) // called function
{
int res;
res=*p1+*p2;
printf(“Result is %d”,res);
}

• C Program to find area of triangle using pointers (call by reference) as Parameters to a


function:
#include<stdio.h>
void area(float *, float *);
void main()
{
float b, h, *p1, *p2;
printf(“enter breadth and height:\n”);
scanf(“%f %f”, &b, &h);
p1=&b;
p2=&h;
add(p1,p2);
}
void area(int *p1, int *p2) // called function
{
float area;
res=0.5(*p1**p2);
printf(“Result is %f”,area);
}
DYNAMIC MEMORY MANAGEMENT: While programming, if you are aware of
the size of an array, then it is easy and you can define it as an array. For example, to store a name
of any person, it can go up to a maximum of 100 characters, so you can define something as
follows:

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:

• malloc() - “malloc” or “memory allocation” method in C is used to dynamically allocate a


single large block of memory with the specified size.
➢ Syntax: ptr = (data-type*)malloc(n*sizeof(data-type));

• calloc() - “calloc” or “contiguous allocation” method in C is used to dynamically allocate the


specified number of blocks of memory of the specified type.
➢ Syntax: ptr = (data-type*)calloc(n, sizeof(data-type));

• 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);

• realloc() - “realloc” or “re-allocation” method in C is used to dynamically change the


memory allocation of a previously allocated memory. In other words, if the memory
previously allocated with the help of malloc or calloc is insufficient, realloc can be used to
dynamically re-allocate memory.
➢ Syntax: ptr = (data-type*)realloc(ptr, new_size);

• 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);
}

You might also like