PPS Unit 4 Notes Full
PPS Unit 4 Notes Full
Unit – IV
Pointers: Pointer declaration, compatibility, Operations on pointers, Pointers and arrays, Pointers
and functions.
Structures: Structure definition, Array of structures, Nested structures, Passing structure to
functions,Pointers and structures, Self-referential structures, Unions, enumerated data types.
Definition:
Pointers: A pointer is a variable that holds the address of another variable. The pointer variable
contains only the address of the referenced variable not the value stored at that address.
4. Pointers provide an efficient tool for manipulating dynamic data structures such as
6. Pointers reduce program execution time and saves data storage space in memory.
Disadvantages of pointers
1. One of the disadvantage of using pointer is that program may crash if sufficient memory
1
Programming for problem solving unit 4 Notes
2. The indirection operator (*):It is used to accesses the object the pointer points to.
Datatype *ptrname;
Data type: It specifies the type of the pointer variable that you want to declare like (int, float, char,
double or void)
* (Asterisk): tells the compiler that you are creating a pointer variable and ptrname specifies the name
of the pointer variable.
Initialization of pointer variable: Similar to the initialization of other variables at the time of their
declaration, you can also initialize the pointer variable by assigning address of other variables to them.
Syntax
Where
#include<stdio.h>
2
Programming for problem solving unit 4 Notes
void main()
int a=10;
Output:
Using the address of (&) operator: A computer uses memory to store the instructions of different
programs and the values of different variables. Since memory is a sequential collection of storage cells,
each cell has an address. When you declare a variable, the operating system allocates memory according
to the size of the data type of that variable. In this memory location, the value of the variable is stored.
This statement request the operating system to allocate two bytes of space in memory and stores
a ----------→variable name
By using the address of (&) operator, you can determine the address of a variable.
3
Programming for problem solving unit 4 Notes
4
Programming for problem solving unit 4 Notes
5
Programming for problem solving unit 4 Notes
Pointer Compatibility:
The rules for assigning one pointer to another are tighter than the rules for
numeric types. For example, you can assign an int value to a double variable without
using a type conversion, but you can’t do the same for pointers to these two types.•
We can assign an int valur to double variable without type conversion,but the same cannot
be true for pointers.
Example Program
#include,stdio.h>
int main()
int n=5;
long double x;
int *pi=&n;
x=n;
pld=pi;
return 0;
• Size of all pointers is the same; i.e.; every pointer variable holds the address of one
memory location. But the size of variable that the pointer points to can be different.
• Size of the type that a pointer points to is same as its data size.
Dereferencing Compatibility
• It is usually invalid to assign a pointer of one type to address of a variable of another type.
7
Programming for problem solving unit 4 Notes
unsigned integer value i.e., it is a numerical value. So we can perform arithmetic operations on
pointer values. But when we perform arithmetic operations on pointer variable, the result
depends on the amount of memory required by the variable to which the pointer is pointing.
pointers...
8
Programming for problem solving unit 4 Notes
int main()
{
int a = 22;
int *p = &a;
printf("p = %u\n", p); // p = 6422288
p++;
printf("p++ = %u\n", p); //p++ = 6422292 +4 // 4 bytes
p--;
printf("p-- = %u\n", p); //p-- = 6422288 -4 // restored to original value
float b = 22.22;
float *q = &b;
printf("q = %u\n", q); //q = 6422284
q++;
printf("q++ = %u\n", q); //q++ = 6422288 +4 // 4 bytes
q--;
printf("q-- = %u\n", q); //q-- = 6422284 -4 // restored to original value
char c = 'a';
char *r = &c;
printf("r = %u\n", r); //r = 6422283
r++;
printf("r++ = %u\n", r); //r++ = 6422284 +1 // 1 byte
r--;
printf("r-- = %u\n", r); //r-- = 6422283 -1 // restored to original value
return 0;
}
Output:
p = 1441900792
9
Programming for problem solving unit 4 Notes
p++ = 1441900796
p-- = 1441900792
q = 1441900796
q++ = 1441900800
q-- = 1441900796
r = 1441900791
r++ = 1441900792
r-- = 1441900791
2. Addition of Integer to Pointer
When a pointer is added with an integer value, the value is first multiplied by the size of the
data type and then added to the pointer.
For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as an
address. If we add integer 5 to it using the expression, ptr = ptr + 5, then, the final address
stored in the ptr will be ptr = 1000 + sizeof(int) * 5 = 1020.
#include <stdio.h>
// Driver Code
int main()
// Integer variable
int N = 4;
10
Programming for problem solving unit 4 Notes
// Pointer to an integer
ptr1 = &N;
ptr2 = &N;
// Addition of 3 to ptr2
ptr2 = ptr2 + 3;
return 0;
Output
Pointer ptr2 before Addition: 0x7ffca373da9c
Pointer ptr2 after Addition: 0x7ffca373daa8
3. Subtraction of Integer to Pointer
When a pointer is subtracted with an integer value, the value is first multiplied by the size of
the data type and then subtracted from the pointer similar to addition.
For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as an
address. If we subtract integer 5 from it using the expression, ptr = ptr – 5, then, the final
address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.
Example of Subtraction of Integer from Pointer
#include <stdio.h>
11
Programming for problem solving unit 4 Notes
// Driver Code
int main()
// Integer variable
int N = 4;
// Pointer to an integer
ptr1 = &N;
ptr2 = &N;
// Subtraction of 3 to ptr2
ptr2 = ptr2 - 3;
return 0;
Output
Pointer ptr2 before Subtraction: 0x7ffd718ffebc
Pointer ptr2 after Subtraction: 0x7ffd718ffeb0
4. Subtraction of Two Pointers
The subtraction of two pointers is possible only when they have the same data type. The result
is generated by calculating the difference between the addresses of the two pointers and
calculating how many bits of data it is according to the pointer data type. The subtraction of
two pointers gives the increments between the two pointers.
ForExample:
Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are
12
Programming for problem solving unit 4 Notes
subtracted. The difference between addresses is 4 bytes. Since the size of int is 4 bytes,
therefore the increment between ptr1 and ptr2 is given by (4/4) = 1.
// of two pointers
#include <stdio.h>
// Driver Code
int main()
int N = 4;
// Pointer declaration
x = ptr1 - ptr2;
13
Programming for problem solving unit 4 Notes
x);
return 0;
Output
ptr1 = 2715594428, ptr2 = 2715594424
Subtraction of ptr1 & ptr2 is 1
5. Comparison of Pointers
We can compare the two pointers by using the comparison operators in C. We can implement
this by using all operators in C >, >=, <, <=, ==, !=. It returns true for the valid condition and
returns false for the unsatisfied condition.
1. Step 1: Initialize the integer values and point these integer values to the pointer.
2. Step 2: Now, check the condition by using comparison or relational operators on
pointer variables.
3. Step 3: Display the output.
#include <stdio.h>
int main()
// declaring array
int arr[5];
if (ptr1 == ptr2) {
14
Programming for problem solving unit 4 Notes
"are Equal.");
else {
return 0;
Output
Pointer to Array Name and First Element are Equal.
Pointers and arrays
In the c programming language, when we declare an array the compiler allocate the required
amount of memory and also creates a constant pointer with array name and stores the base
address of that pointer in it. The address of the first element of an array is called as base
address of that array.
The array name itself acts as a pointer to the first element of that array. Consider the following
example of array declaration...
Example Code
int marks[6] ;
For the above declaration, the compiler allocates 12 bytes of memory and the address of first
memory location (i.e., marks[0]) is stored in a constant pointer called marks. That means in the
above example, marks is a pointer to marks[0].
Example Program
#include<stdio.h>
#include<conio.h>
int main()
{
int marks[6] = {89, 45, 58, 72, 90, 93} ;
15
Programming for problem solving unit 4 Notes
int *ptr ;
ptr = marks ;
printf(“Base Address of 'marks' array = %u\n”, ptr) ;
return 0;
}
Output:
2. We can use the array name to access the address and value of all the elements of
that array.
Example Code
ptr = marks + 2 ;
Here, the pointer variable "ptr" is assigned with address of "marks[2]" element.
Example Code
Example Code
In the above two statements, first printf statement prints the value 89 (i.e., value of marks[0]) and
the second printf statement prints the value 72 (i.e., value of marks[3]).
16
Programming for problem solving unit 4 Notes
Example Code
marks++ ;
The above statement generates compilation error because the array name acts as a constant
pointer. So we can't change its value.
In the above example program, the array name marks can be used as follows...
Example program Display the elements of an array in reverse order using pointers
#include<stdio.h>
#define N 5
int main()
{
int a[N], i, *ptr;
printf("Enter %d integer numbers\n", N);
for(i = 0; i < N; i++)
scanf("%d", &a[i]);
ptr = &a[N - 1];
printf("\nElements of array in reverse order ...\n");
for(i = 0; i < N; i++)
printf("%d\n", *ptr--);
return 0;
}
Find the biggest and smallest elements of an array using pointer to an array
#include<stdio.h>
#define N 5
int main()
{
17
Programming for problem solving unit 4 Notes
// Driver code
int main()
{
int a = 10, b = 20;
printf("Values before swap function are: %d, %d\n",
a, b);
swap(&a, &b);
printf("Values after swap function are: %d, %d",
a, b);
18
Programming for problem solving unit 4 Notes
return 0;
}
The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the C
programming language. The items in the structure are called its member and they can be of
any valid data type.
C Structure Declaration
We have to declare structure in C before using it in our program. In structure declaration, we
specify its member variables along with their datatype. We can use the struct keyword to
declare the structure in C using the following syntax:
Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
The above syntax is also called a structure template or structure prototype and no memory is
allocated to the structure in the declaration.
C Structure Definition
To use structure in our program, we have to define its instance. We can do that by creating
variables of the structure type. We can define structure variables using two methods:
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;
Struct Employee
{
int empno; //2 bytes
char ename[20]; //20 bytes
19
Programming for problem solving unit 4 Notes
int main()
{
Struct Employee e1,e2,e3;
}
Access Structure Members
➢ We can access structure members by using the ( . ) dot operator.
Syntax
structure_name.member1;
structure _name.member2;
In the case where we have a pointer to the structure, we can also use the arrow operator to
access the members.
Example:
e1.empno;
e1.ename;
e1.salary
Initialize Structure Members
Structure members cannot be initialized with the declaration. For example, the following C
program fails in the compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
Example1 Program:WAP to display the size of structure and to display the employee details
#include<stdio.h>
Struct Employee
{
int empno; //2 bytes
char ename[20]; //20 bytes
float empsal; // 4 bytes
20
Programming for problem solving unit 4 Notes
};
Void main()
Printf(“Employee number=%d”,e.empno);
Printf(“Employee number=%s”,e.ename);
Printf(“Employee number=%d”,e.salary);
Example 2:
#include<stdio.h>
Struct student
{
char name[40];
int roll;
float marks;
}s;
Void main()
Strcpy(s.name,”Matrusri”);
S.roll=100;
s.marks=25;
Printf(“Rollnumber=%d”,s,roll );
Printf(“Marks=%f”, s.marks);
Example 3: To store N students’ details (name, roll no, subject1, subject2, subject3 marks),
compute average_marks, and display the grade of each student.
#include<stdio.h>
Struct student
char name[20];
int rollno;
float subject1,subject2,subject3;
float avg;
float tot;
};
int main()
scanf(“%s”,&s1.name);
scanf(“%d”,s1.rollno);
s1.tot=(s1.subject1+s1.subject2+s1.subject3);
s1.avg=(s1.tot)/3;
22
Programming for problem solving unit 4 Notes
printf(“Total=%f,Average=%f”,s1.tot,s1.avg);
if(s1.avg>=75)
printf(“Grade A”);
printf(“Grade B”);
printf(“Grade C”);
else
printf(“Fail”);
return 0;
ARRAY OF STRUCTURES IN C:
An array of structures is a way of storing multiple data items of the same type in a single
variable. Each data item is called an element of the array, and each element has one or more
fields that store different kinds of information. For example, you can use an array of structures to
store the details of several employees, such as their name, ID, and attendance.
To declare an array of structures, you need to first define the structure type, and then specify the
array name and size. For example:
struct Employee {
char Name[20];
int employeeID;
int WeekAttendance[7];
};
This declares an array of structures called emp, which can store up to 5 elements of type struct
Employee. Each element has three fields: Name, employeeID, and WeekAttendance.
23
Programming for problem solving unit 4 Notes
To initialize an array of structures, you can use curly braces to assign values to each element and
field. For example:
This initializes the array of structures with 5 elements, each with a name, an ID, and a 7-element
array of integers representing the attendance for each day of the week.
To access an element or a field of an array of structures, you can use the array index and the dot
operator. For example:
// Access an element of an array of structures
printf("Employee Name: %s\n", emp[0].Name); // Prints Alice
#include<stdio.h>
struct student
char id[10];
char name[15];
int m1;
int m2;
int tot;
};
void main()
{
24
Programming for problem solving unit 4 Notes
int i;
for(i=0;i<3;i++)
printf("\n\n");
Example 2:WAP to display the employee details using arrays and structures
#include<stdio.h>
struct employee
int empno;
char ename[20];
float salary;
};
void main()
int i;
25
Programming for problem solving unit 4 Notes
for (i=0;i<3;i++)
scanf(‘%d%s%f”,&e[i].empno,&e[i].ename,&e[i].salary);
for(i=0;i<3;i++)
Nested structures
Syntax:
struct name_1
{
member1;
member2;
.
.
member n;
struct name_2
member_1;
member_2;
.
26
Programming for problem solving unit 4 Notes
member_n;
}, var1
} var2;
27
Programming for problem solving unit 4 Notes
struct student
int id;
char name[20];
struct dob
int day,mm,yy;
}d;
};
int main()
{
Struct student s;
Printf(“ enter the student ID”);
scanf(“%d”,&s.id);
printf(“enter the student name:”);
scanf(“%s”,&s,name);
printf(“enter the date of birth:”);
scanf(“%d%d%d”,&s.d.day,&s.d.mm,&s.d.yy);
printf(“\n student details are:”);
printf(“\n student id=%d”,s.id);
printf(“\n student name=%s”,s.name);
printf(“ student date of birth=%d-%d-%d”,s.d.day,s.d.mm,s.d.yy);
return 0;
}
28
Programming for problem solving unit 4 Notes
#include<stdio.h>
struct student
}s;
char id[10];
char name[20];
float m;
show(char[],char[],float);
void main()
clrscr();
printf("\nEnter id:");
gets(s.id);
gets(s.name);
scanf("%f",&s.m);
show(s.id,s.name,s.m);
getch();
29
Programming for problem solving unit 4 Notes
printf(" %s %s %f",sid,sname,score);
O/P:
printf(" %s %s %f",sid,sname,score);
ID NAME MARKS
Instead of passing individual members we can pass the entire structure to a function
struct student
char id[10];
char name[20];
float m;
}s;
void main()
printf("\nEnter id:");
30
Programming for problem solving unit 4 Notes
gets(s.id);
gets(s.name);
scanf("%f",&s.m);
show(s);
getch();
show(struct student p)
printf(" %s \t %s \t %f",p.id,p.name,p.m);
#include<stdio.h>
struct student
char id[10];
char name[20];
float m;
}s;
void main()
31
Programming for problem solving unit 4 Notes
printf("\nEnter id:");
gets(s.id);
gets(s.name);
scanf("%f",&s.m);
show(&s);
getch();
printf(" %s \t %s \t %f",p->id,p->name,p->m);
O/P:
Enter id:Mahi
ID NAME MARKS
32
Programming for problem solving unit 4 Notes
trees, graphs, etc. are created with the help of structure pointers. The structure pointer tells the
address of a structure in memory by pointing the variable to the structure variable.
Syntax:
Struct student s;
Ptr=&s;
struct point
{
int value;
};
int main()
{
struct point s;
return 0;
}
There are two ways to access the members of the structure with the help of a
structure pointer:
1. With the help of (*) asterisk or indirection operator and (.) dot
operator.
2. With the help of ( -> ) Arrow operator.
33
Programming for problem solving unit 4 Notes
Below is the program to access the structure members using the structure
pointer with the help of the dot operator.
// C Program to demonstrate Structure pointer
#include <stdio.h>
#include <string.h>
struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};
int main()
s1.roll_no = 27;
s1.batch = 2019;
return 0;
34
Programming for problem solving unit 4 Notes
Below is the program to access the structure members using the structure pointer with the help
of the Arrow operator. In this program, we have created a Structure Student containing
structure variable s. The Structure Student has roll_no, name, branch, and batch.
int main()
{
ptr = &s;
printf("Enter the Roll Number of Student\n");
scanf("%d", &ptr->roll_no);
printf("Enter Name of Student\n");
scanf("%s", &ptr->name);
printf("Enter Branch of Student\n");
scanf("%s", &ptr->branch);
printf("Enter batch of Student\n");
scanf("%d", &ptr->batch);
return 0;
}
35
Programming for problem solving unit 4 Notes
Self-referential structures
A structure which contains a member that points to the same structure type is called “self
referential structure”.
Example:
Struct self
Int p;
};
Struct code
Int I;
Char c;
};
Int main()
var1.i=65;
var1.c=’h’;
var1.ptr=null;
var2.i=75;
var2.c=’j’;
36
Programming for problem solving unit 4 Notes
var2.ptr=null;
var1.ptr=&var2;
printf(“%d%c”,var1.ptr->i,var1.ptr->c)
65 H 2000 75 J NULL
NULL
Var1.ptr=&var 2
Ouput:
75 J
#include<stdio.h>
37
Programming for problem solving unit 4 Notes
union student
char name[15];
int m1;
float m2;
};
void main()
strcpy(u.name,"Raj");
printf("\nHello %s",u.name);
u.m1=88;
printf("\nMarks1= %d",u.m1);
u.m2=96.57;
printf("\nMarks2= %f",u.m2);
/*if we assign all at once as follows observe the output... No need to write the below code in the
strcpy(u.name, "Ravi");
u.m1=88;
u.m2=96.57;
getch();
Output:
Hello Raj
Marks1= 88
38
Programming for problem solving unit 4 Notes
Marks2= 96.570000
Marks1=9175 /*Garbage*/
#include <stdio.h>
union test1
{
int x;
int y;
} Test1;
union test2
{
int x;
char y;
} Test2;
union test3
{
int arr[10];
char y;
} Test3;
// driver code
int main()
{
// finding size using sizeof() operator
int size1 = sizeof(Test1);
int size2 = sizeof(Test2);
int size3 = sizeof(Test3);
39
Programming for problem solving unit 4 Notes
Structure Union
The size of the structure is equal to or greater The size of the union is the size
than the total size of all of its members. of its largest member.
The structure can contain data in multiple Only one member can contain
members at the same time. data at the same time.
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of
constant integrals or integers that are given names by a user. The use of enum in C to name the
integer values makes the entire program easy to learn, understand, and maintain by the same or
even different programmer.
// Or
Example Program1
#include<stdio.h>
int main()
{
enum week day;
day = Wed;
40
Programming for problem solving unit 4 Notes
printf("%d",day);
return 0;
}
Output:
Example Program2
#include<stdio.h>
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
return 0;
}
Output:
0 1 2 3 4 5 6 7 8 9 10 11
#include <stdio.h>
enum State {Working = 1, Failed = 0, Freezed = 0};
int main()
{
printf("%d, %d, %d", Working, Failed, Freezed);
return 0;
}
Output:
1, 0, 0
2. If we do not explicitly assign values to enum names, the compiler by default assigns values
starting from 0. For example, in the following C program, sunday gets value 0, monday gets 1,
and so on.
41
Programming for problem solving unit 4 Notes
#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
return 0;
}
Output:
The day number stored in d is 4
3. We can assign values to some name in any order. All unassigned names get
value as value of previous name plus one.
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,
wednesday, thursday = 10, friday, saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,
wednesday, thursday, friday, saturday);
return 0;
}
Output:
1 2 5 6 10 11 12
4. The value assigned to enum names must be some integral constant, i.e., the value must be in
range from minimum possible integer value to maximum possible integer value.
5. All enum constants must be unique in their scope. For example, the following program fails
in compilation.
Output:
Compile Error: 'failed' has a previous declaration as 'state failed'
42
Programming for problem solving unit 4 Notes
Important Questions:
43