PC Unit Iv Notes
PC Unit Iv Notes
UNIT IV
4.6: POINTERS-DEFINITION
4.12:SIMPLE PROGRAMS
1
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
Self referential structures are those structures that contain a reference to data of its
same type. That is it contains the pointer to the data that is of same type of as that of the
structure.
struct node
{
int val;
struct node *next;
};
Here the structure node will contain two types of data- an integer val and next that is a
pointer
to a node.
10. What is a pointer? List out the advantages of using pointer. (JAN-2016, MAY-
2015, MAY-2014,JAN-2013,MAY-2012, JAN 2010,May-2019)
A pointer is a special type of variable which holds the address or location of another
variable. It is declared in the same fashion like other variables but it is always denoted by ‘*’
operator.
Example:
int a, *p;
a=5;
Advantages: P=&a;
1. For accessing a variable that is defined outside the function.
2. For efficient handling of data tables.
3. For reducing the size and complexity of programs.
4. For increasing the execution speed.
5. For saving the storage space by using the pointer arrays for character stings.
Enumerated type:
This is also a user defined data type. “Enum” is the keyword and “identifier” is the user
defined data type that is used to declare the variables. It can have any value enclosed within
the curly braces.
Syntax:
enum identifier {value1,value2, value 3,…}
For example:
enum day {January,February,March,April,..};
3
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
Nesting of structures are nothing but structure within another structure (i.e., a
structure can contain one or more structures embers).
A structure may be defined and/or declared inside another structure.
struct employee
{
int empno;
char name[15];
struct dob
{
int date ,
int month,
int year;
} d;
}emp;
15. Write the syntax for declaration and initialization of structures. (JAN 2011)
Syntax:
struct structure_name
{
data type data member1;
4
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
}book1;
The members of a structure themselves are not variables. They do not occupy any
memory until they are associated with the structure variables such as book1. When the
compiler comes across a declaration statement, it reserves memory space for the structure
variables. It is also allowed to combine both the structure definition and variables declaration
in one statement.
18. Write a program using pointer to determine the length of a character strings?
main()
{
char *name;
int length;
char *cptr=name;
name=”DEHI”;
printf(“%s\n”,name);
while(cptr!=’\0’)
{
printf(“%c is stored at address %u\n”,*cptr,cptr);
cptr++;
}
length=cptr-name;
printf(“\nlength of the string=%d\n””,length);
}
The enum is a keyword. It is used for declaring enumeration types. The programmer
can create his/her own data type and define what values the variables of these data types can
hold. This enumeration data type helps in reading the program.
Syntax:
enum tag{member1,member2,...........member n};
b=10 value
1008 address
25. Write the advantages of using Pointers. (or) Uses of pointers. ( Jan 2012)
Pointers are more compact and efficient code.
Pointers can be used to achieve clarity and simplicity.
Pointers are used to pass information between function and its reference point.
Pointers enable us to access the memory directly.
26. Define Pointer to Pointer.
It is a variable that contains the address of another variable. Similarly another pointer
variable can store the address of this pointer variable. This is known as Pointer to Pointer.
29. What are an address operator and indirection operator? (NOV/DEC 2014,2015)
6
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
The indirection operator (*) accesses a value indirectly, through a pointer. The operand must
be a pointer value. The result of the operation is the value addressed by the operand; that is,
the value at the address to which its operand points.
c=*p1 * p2 - *p1/*p2+9;
printf(“%d”,c);
PART – B Questions
DECLARATION OF STRUCTURES
It contains data members and each is accessed by the structure variable. A structure
is declared using the keyword struct followed by a structure name. All the variables of the
structures are declared within the structure.
7
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
Syntax:
struct structure_name
{
structure_element 1;
structure_element 2;
Example:
--------
--------
structure_element n;
};struct structure_name v1,v2,…,vn;
struct student
{
int marks;
float avg;
char grade;
};
The structure definition does not allocate any memory. Structure provides a model of how
the structure is to be in memory and gives details of the member names. Memory is allocated
for the structure when we declare a variable of the structure.
struct student
{
int marks;
float avg;
char grade;
}s; // Declaring Structure Variable
int marks
float avg
avg grade
INITIALIZATION OF STRUCTURES
Initializing a structure means assigning some constants to the members of the structure. The
initializes are enclosed in braces and are separated by commas.
Example:
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
}struct student stud1 = {01, “Rahul”, “IT”, 45000};
Array elements are accessed using the Subscript variable, Similarly Structure members
are accessed using dot [.] operator. It is called as “Structure member Operator”. Use this
Operator in between “Structure name” & “member name”
Syntax:
struct_var.member_name;
Example:
stud1.rno = 01;
strcpy(stud1.name, “Kalam”);
stud1.course = “IT”;
stud1.fees = 45000;
Selecting a member from a structure pointer happens frequently, it has its own
operator -> which acts as follows. Assume that stud1 is a pointer to a structure of type
student we would refer to the name member as
stud1.rno->name
#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[80];
float fees;
char DOB[80];
};
int main()
{
struct student stud1;
clrscr( );
printf(“\n Enter the roll number : “);
scanf(“%d”, &stud1.rollno);
printf(“\n Enter the name : “);
scanf(“%s”, stud1.name);
printf(“\n Enter the fees : “);
scanf(“%f”, &stud1.fees);
printf(“\n Enter the DOB : “);
scanf(“%s”, stud1.DOB);
printf(“\n ********STUDENT’S DETAILS *******”);
printf(“\n ROLL No. = %d”, stud1.rollno);
printf(“\n NAME. = %s”, stud1.name);
printf(“\n ROLL No. = %f”, stud1.fees);
printf(“\n ROLL No. = %s”, stud1.DOB);
getch( );
}
OUTPUT:
Enter the roll number : 101
Enter the name : rahul
Enter the fees : 45000
Enter the DOB : 11.2.1995
9
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
Syntax
struct struct_name struct_var[index];
Example
struct student stud[30];
Now, to assign values to the ith student of the class, we will write,
stud[i].r_no = 09;
stud[i].name = “RAM”;
stud[i].course = “CSE”;
stud[i].fees = 60000;
/*program to read and display information of all the students in the class*/(May-
2019)
#include<stdio.h>
#include<conio.h>
struct studentinfo
{
int roll;
char name[20];
int age;
};
void main()
{
struct studentinfo s[100];
clrscr();
int n,i;
printf("\nHow many students information do you want to enter?");
scanf("%d",&n);
printf("Enter Student Information:");
for(i=1;i<=n;i++)
{
printf("\nEnter Roll no.:");
scanf("%d",&s[i].roll);
printf("\nEnter the name of the student:");
scanf("%s",&s[i].name);
printf("\nEnter the age of the student:");
scanf("%d",&s[i].age);
}
printf("\n\nInformation of all studenst:");
for(i=1;i<=n;i++)
{
printf("\nRoll no.:%d",s[i].roll);
printf("\nName:%s",s[i].name);
10
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
printf("\nAge of student:%d\n\n",s[i].age);
}
getch( );
}
C permits the use of arrays as structure members. We have already used arrays of
characters inside a structure. Similarly, we can use single-dimensional or multidimensional
arrays of type int or float. For example, the following structure declaration is valid:
struct marks
{
int number;
float subject[3];
} student[2];
Here the member structure subject contains three elements, subject[0], subject[1],
subject[2]. These elements can be accessed using appropriate subscripts. For example, the
name, student[1].subject[2];
would refer to the marks obtained in the third subject by the second student.
11
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
printf("\nSUBJECT TOTAL\n\n");
for(j = 0; j <= 2; j++)
printf("Subject-%d %d\n", j+1, total.sub[j]);
}
Output:
STUDENT TOTAL
Student[1] 193
Student[2] 197
Student[3] 164
SUBJECT TOTAL
Subject-1 177
Subject-2 156
Subject-3 221
[ Univ. Ques. Jan 2016, May 2015, Jan 2015, May 2013]
NESTED STRUCTURES
A structure can be placed within another structure. That is, a structure may contain
another structure as its member. Such a structure that contains another structure as its
member is called a nested structure.
12
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
Example:
/*Program to read and display the information of student using nested
Structure*/
#include<stdio.h>
#include<conio.h>
struct DOB
{
int day;
int month;
int year;
};
struct student
{
int roll_no;
char name[100];
float fees;
struct DOB date;
};
int main( )
{
OUTPUT:
13
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
Similar to arrays and pointers a structure can also be passed to a function. There are
three ways of passing a structure to a function.
They are;
This method is used to pass each member of the structure as an actual argument
of the function call statement.
For example;
struct employee
{
int empno;
char empname[20];
float salary;
} emp;
employ(emp.empno)
employ(emp.empname)
employ(emp.salary);
This method is the most common method and becomes inefficient when the structure
is large.
The member of a structure can also be passed to function by passing the address
of the members.
In this, a method the address location of the members is passed to the called
function, hence the address operator (&) is used before the structure name.
In this method, the entire structure is passed as an argument to the function, since
the function is working on a copy of the structures, any changes made to the structure
members within the function are not reflected in the original structure. Therefore, it is
necessary for the function to return the entire structure back to the calling function.
Example: /* Function struct.c */
#include<stdio.h>
void employ(struct employee emp);
struct employee
{
int empno;
char empname[20];
};
main()
{
struct employee emp1;
printf(“\nEnter Employee No. and Name : “);
scanf(“%d%s”,&emp1.empno,emp1.empname);
employ(emp1);
}
void employ(struct employee emp)
{
printf(“\nThe Employee No. is : %d”, emp.empno);
printf(“\nThe Employee Name is : %s”, emp.empname);
}
OUTPUT:
15
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
Self referential structures are those structures that contain a reference to data of its
same type. That is, a self referential structure in addition to other data contains a pointer to
a data that is of the same type as that of the structure. For example, consider the structure
node given below.
struct node
{
int item;
struct node *next;
};
Here the structure node will contain two types of data- an integer item and next that is a
pointer to a node. Self-referential structure is the foundation of other data structures. They
are most commonly used in linked list data structure implementation
Example:
#include <stdio.h>
#include<conio.h>
struct stud
{
int roll;
char name[30];
int age;
struct stud *next; // self reference
structure
}
16
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
void main()
{
struct stud n1, n2, n3;
struct stud *p;
clrscr( );
printf("Enter the details of students");
scanf ("%d %s %d", &n1.roll, n1.name, &n1.age);
scanf ("%d %s %d", &n2.roll, n2.name, &n2.age);
scanf ("%d %s %d", &n3.roll, n3.name, &n3.age);
n1.next = &n2; //assigning address of the structure
n2.next = &n3;
n3.next = NULL;
p = &n1; /* point to 1stelement */
printf(“\n The students details are:”);
while (p != NULL)
{
printf ("\n %d %s %d", p->roll, p->name, p->age);
p = p->next;
}
getch( );
}
OUTPUT:
Enter the details of students
101 ram 19
102 raj 19
103 rahul 18
The students details are:
101 ram 19
102 raj 19
103 rahul 18
15
Explanation:
The list consists of three nodes n1, n2 and n3 by declaring struct stud n1, n2, n3. To create
the links between nodes, we write n1.next = &n2; n2.next = &n3; By pointing the address
of the first element, and while loop we can traverse through the nodes and display the
student details.
6. SIZE OF STRUCTURES
We normally use structures, unions and arrays to create variables of large sizes. The
actual size of these variables in terms of bytes may change from machine to machine. We
may use the unary operator sizeof to tell us the size of a structure (or any variable). The
expression
sizeof(struct x)
we evaluate the number of bytes required to hold all the members of the structure x. If y is a
simple structure variable of type struct x, then the expression
sizeof(y)
would also give the same answer. However, if y is an array variable of type struct x, then
sizeof(y)
would give the total number of bytes the array y requires.
This kind of information would be useful to determine the number of records in a
database. For example, the expression
sizeof(y)/sizeof(x)
would give the number of elements in the array y.
17
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
7. BIT FIELD
Bit field is used to hold data items. It helps in direct manipulation of string.
The size of bit field may be from 1 to 16 bits in Length.
The name and size of bit field are defined using structure.
#define FAIL 0
#define PASS 1
#define A 1
#define B 2
#define C 3
main()
{
Struct std
{
Int rno;
unsigned result : 1;
unsigned grade : 2;
};
struct std s;
s.rno=9207;
s.result=PASS;
s.grade=A;
clrscr();
printf(“Roll Number....%d\n”, s.rno”);
printf(“Results.....%d\n”, s.result”);
printf(“Grade....%d\n”, s.grade”);
s.rno=9207;
s.result=PASS;
s.grade=B;
printf(“Roll Number....%d\n”, s.rno”);
18
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
printf(“Results.....%d\n”, s.result”);
printf(“Grade....%d\n”, s.grade”);
s.rno=9207;
s.result=PASS;
s.grade=C;
printf(“Roll Number....%d\n”, s.rno”);
printf(“Results.....%d\n”, s.result”);
printf(“Grade....%d\n”, s.grade”);
}
Output:
Roll Number...9207
Results............1
Grade..............1
Roll Number...9382
Results............1
Grade..............1
Roll Number...9556
Results............1
Grade..............3
TYPEDEF
Example: C Program to create user defined data type weeks on int data type
and used it in the program.
19
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
#include<stdio.h>
#define D 7
void main
{
typedef int weeks;
weeks wk;
printf(“Enter weeks: ”);
scanf(“%d”, &wk);
printf(“Number of days = %d”, wk*D);
}
Output:
Enter weeks: 4
Number of days = 28
Example:
int *a;
float *b;
20
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
char *c;
Explanation
int rno=40;
rno Variable
40 Value
2005 Address
Let as assume that the system has assign the address location as 2005 for a variable ‘sno’.
FEATURES OF POINTERS
Pointers are efficient in handling data.
Pointers are used for saving memory space.
Pointers reduce the length and complexity of the program.
The execution time is faster.
ADVANTAGES OF POINTERS
Pointers are more compact and efficient code.
Pointers can be used to achieve clarity and simplicity.
Pointers are used to pass information between function and its reference point.
Pointers enable us to access the memory directly.
#include<stdio.h>
#include<conio.h>
main ( )
{
int a=22, int *a;
clrscr();
a=&a;
printf ("\n Value of a=%d", *a);
printf ("\n Address of a=%u", &a);
printf ("\n Value at address %u=%d", &a, *(&a));
}
Output:
Value of a=22
Address of a=4000
value at address 4000=22
21
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
When users declare an array the consecutive memory locations are located to the
array of elements. The elements of an array can be efficiently accessed by using pointers.
Example:
int a[5]={10,20,30,40,50};
10 20 30 40 50 value
The base address of the array starts with 0 th element of the array. The array is in
integer type.
The integer will have 2 bytes.
The address of the next address element is incremented by 2.
Program:
#include<stdio.h>
main( )
{
int i,total,a[5],*c;
for(i=0;i<5;i++)
{
printf("\nEnter the number %d:”,i+1);
scanf("%d",&a[i]);
}
c=a;
for(i=0;i<5;i++)
{
total=total+*c;
c=c+1;
}
printf("\n Total=%d",total);
}
Output:
Enter the number 1:10
Enter the number 2:20
Enter the number 3:30
Enter the number 4:40
Enter the number 5:50
22
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
Total=150
NULL POINTER
A Pointer is said to be a null pointer when its right value is 0.
Example:
int *a;
int *b;
b=a=0;
Pictorial Representation
Note:
Example:
int a=20;
int *b;
int **c;
b=&a;
c=&b;
Program:
#include<stdio.h>
main()
{
int a=20, int *b;
int **c;
23
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
b=&a;
c=&b;
printf(“Value of a is %d\n”,a);
printf(“Value of a is %d\n”,*(&a));
printf(“Value of a is %d\n”,*b);
printf(“Value of a is %d\n”,**c);
printf(“Value of b and address of a=%u\n”,b);
printf(“Address of a is %u”,&a);
printf(“Address of b is %u”,&b);
printf(“Address of a is %u”,*c);
printf(“Address of b is %u”,&b);
printf(“Address of b is %u”,c);
printf(“Address of c is %u”,&c);
getch();
}
Output:
Value of a is 20
Value of a is 20
Value of a is 20
Value of a is 20
Value of b and address of a=2005
Address of a is 2005
Address of b is 2005
Address of a is 2005
Address of b is 2005
Address of b is 2005
Address of c is 2005
Syntax:
char *pointer_character;
A character pointer can also be used to access character arrays and string constants,
in the same way as accessing numeric arrays using their respective pointer variable.
Pointer variables can be used in expressions. As a user, we can use integer for addition and
subtraction from pointers.
Example:
Another Example:
In the above two method, especially ‘call by reference’ is used to achieve the technique of
‘Pointers and Functions’
The calling function sends the addresses of the variables and the called function must
declare those incoming arguments as pointers.
In order to modify the variables sent by the caller, the called function must
dereference the pointers that were passed to it.
Thus, passing pointers to a function avoid the overhead of copying data from one
function to another.
This Process is otherwise called as Call by reference.
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main( )
{
int x,y;
clrscr();
printf("Enter the values of a & b\n");
scanf("%d%d",&a,&b);
swap(&a,&b);
printf("A=%d \n B=%d",a,b);
getch( );
}
void swap(int *px,int *py)
{
int pz;
pz=*px;
*px=*py;
*py=pz;
}
Pointer which point structure in the same way as used with the other variable are
called Structure pointers.
25
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
Example:
Program to declare pointer to structure and display the contents of the
structure
#include<stdio.h>
#include<conio.h>
main()
{
struct book
{
char name[25];
char author[25];
int pages;
};
struct book b1={“Computer Programming”, “Kamthane”, 479};
struct book 8ptr;
ptr=&b1;
clrscr();
printf{“\n %s by %s of %d pages”, b1.name, b1.author, b1.pages};
printf{“\n %s by %s of %d pages”, ptr->name, ptr->author, ptr->pages};
}
OUTPUT:
Computer Programming by Kamthane of 479 pages
26
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
Important program
1. Write a C program that gets and displays the report of n students with their personal
and academic details using structures. (, Jan
2010,May/June 2016)
#include<stdio.h>
#include<conio.h>
struct student
{
int rollno,mark1,mark2,mark3,total;
char name[25],grade;
float avg;
}s[50];
main()
{
int i,n;
clrscr();
printf("\nEnter number of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter roll number:");
scanf("%d",&s[i].rollno);
printf("Enter name:");
scanf("%s",s[i].name);
printf("Enter mark 1:");
scanf("%d",&s[i].mark1);
printf("Enter mark 2:");
scanf("%d",&s[i].mark2);
printf("Enter mark 3:");
scanf("%d",&s[i].mark3);
s[i].total=s[i].mark1 + s[i].mark2 + s[i].mark3;
s[i].avg=s[i].total/3;
if(s[i].avg>=75)
{
s[i].grade='S';
}
else if((s[i].avg<75)&&(s[i].avg>=60))
{
s[i].grade='A';
}
else if((s[i].avg<60)&&(s[i].avg>=50))
{
s[i].grade='B';
}
else
{
s[i].grade='C';
}
}
printf("Students details\n");
printf("Roll no Name Mark1 Mark2 Mark3 Total Avg Grade\n");
for(i=0;i<n;i++)
{
printf("%d \t %s \t %d \t %d \t %d \t %d \t %f \t %c \n",
s[i].rollno,s[i].name,s[i].mark1,s[i].mark2,s[i].mark3,s[i].total,s[i].avg,s[i].grade);
}
getch();
}
27
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
OUTPUT
Enter the number of student: 2
Enter roll number: 1
Enter name: Ram
Enter mark1: 50
Enter mark2: 60
Enter mark3: 80
Enter roll number: 2
Enter name: Lakshman
Enter mark1: 98
Enter mark2: 86
Enter mark3: 95
#include<stdio.h>
#include<conio.h>
strcut state
{
char sname[15];
int nec,nmc,nmgc,nsc,total;
}s[20];
main()
{
int i,highest=0;
char shigh[15];
clrscr();
for(i=1;i<=20;i++)
{
printf(“Enter state name:”);
scanf(“%s”,s[i].sname);
printf(“Enter no. Of Engg.colleges:”);
scanf(“%d”,&s[i].nec);
printf(“Enter no. Of medical colleges:”);
scanf(“%d”,&s[i].nmc);
printf(“Enter no. Of Management colleges:”);
scanf(“%d”,&s[i].nmgc);
printf(“Enter no. Of science colleges:”);
scanf(“%d”,&s[i].nsc);
}
printf(“Total colleges in each state\n”);
for(i=1;i<=20;i++)
{
s[i].total=s[i].nec+s[i].nmc+s[i].nmgc+s[i].nsc;
printf(“\n%s,%d”,s[i].sname,s[i].total);
if(s[i].total>highest)
{
highest=s[i].total;
28
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
strcpy(shigh,s[i].sname);
}
}
printf(“\nThe state which is having highest no. Of colleges\n”);
printf(“State Name:%s\n”,shigh);
printf(“Total no. Of colleges:%d\n”,highest);
}
UNIVERSITY QUESTIONS
Part –A
1. What is a self-referential structure? Give example. (JAN-2016)
2. What is a pointer? List out the advantages of using pointer. (JAN-2016, MAY-2015, MAY-
2014,JAN-2013,MAY-2012, JAN 2010)
3. Give an example where a structure data type may be required.
Part –B
29
Sri Manakula Vinayagar Engineering College Unit-4 U23CSTC01- Programming in C
30