Module-5 POINTER Notes
Module-5 POINTER Notes
MODULE-5
POINTERS
Pointers are variables that hold address of another variable of same data type.
Pointers are one of the most distinct and exciting features of C language. It provides
power and flexibility to the language. Although pointer may appear little confusing
and complicated in the beginning, but trust me its a powerful tool and handy to use
once its mastered.
⮚ The basic data types in C language are int float char, double and void.
⮚ Pointer is a special data type which is derived from these data types.
⮚ So pointer is called derived data type.
The pointers are always associated with the following three concept.
● Pointer constants
● Pointer values
● Pointer variables
✔ The computer memory is divided into a number of locations called storage cells.
✔ Each location can hold one byte of information and each location is associated
with address.
✔ These memory address are called pointer constants.
✔ These memory location assigned to variable by the system are called pointer
values.
✔ A variable which holds the address of another variable is called a pointer
variable.
Example: If i is a variable and address of i is stored in a variable P
p=&i;
Then the variable p is called a Pointer variable.
The value 10 can be accessed by either using the variable name a or the
address 80F.Since the memory addresses are simply numbers they can be assigned to
some other variable. The variable that holds memory address are called pointer
variables. A pointer variable is therefore nothing but a variable that contains an
⮚ Dereferencing of Pointer
p Garbage value
#include <stdio.h>
int main()
{
int num1, num2, sum;
int *ptr1, *ptr2;
ptr1 = &num1; // ptr1 stores the address of num1
ptr2 = &num2; // ptr2 stores the address of num2 printf("Enter any two numbers: ");
scanf("%d%d", ptr1, ptr2);
Array Representation
Here variable arr will give the base address, which is a constant pointer pointing to
the element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element
to another. NOTE : You cannot decrement a pointer once incremented. p-- won't
work.
⮚ Pointer to Array
As studied above, we can use a pointer to point to an Array, and then we can use
that pointer to access the array. Lets have an example,
Step 1: [Start]
Step 2: [Input the elements]
Read n, a[i]
Step 3: [Initialize]
sum=0, temp=0
Step 4: [Compute sum, mean, sta dev]
Ptr=a
For i=0 to n
steps of 1 sum=sum+*ptr
Ptr++
Mean=sum/n
Ptr=a
For i=0 to n in steps of 1
temp=temp+pow((*ptr-mean),2)
Ptr++
var=temp/n
std= sqrt(sumstd/n)
Step 5: [Output]
Print sum, mean, standard deviation
Program:
#include main( )
{
int n, i;
float a[20], sum, mean, var, sd;
float *p;
printf(“Enter the value of N\n”);
scanf(“%d”, &n);
printf(“Enter the elements\n”);
for( i = 0; i < n ; i + + )
{
scanf(“%f”, &a[i] );
}
p = a; // p = &a[0];
// To find variance
temp=0.0
for( i = 0; i < n ; i + + )
{
temp = temp + (*(p+i) - mean) * (*(p+i) - mean);
sd = sqrt(var);
return 0;
}
✔ When a function is called with actual parameters, the values of actual parameters
are copied into formal parameters.
✔ If the values of the formal parameters changes in the functions, the values of the
actual parameters are not changed.
After exchange
a=10 and b=20
Before exchange
m=10 and n=20
After exchange
m=20 and n=10
● Pass by reference (call by reference)
✔ In pass by reference, a function is called with addresses of actual parameters.
✔ In the function header, the format parameters receive the addresses of actual
parameters.
✔ Now, the formal parameters do not contain values, instead they contain addresses.
✔ Any variable if it contains an address, it is called a pointer variable.
✔ Using pointer variables, the values of the actual parameters can be changed.
✔ This way of passing parameters is called Pass by reference or call by reference.
C program swapping of two numbers
#include<stdio.h>
Void exchange(int *m, int *n);
void main()
{
int a,b;
❖ Array of Pointers
Array of pointers can also be declared. Pointers are very helpful in handling
character array with rows of varying length.
char *name[3]={
"Adam",
"chris",
"Deniel"
};
//Now see same array without using pointer
char name[3][20]= {
"Adam", "chris",
"Deniel"
};
Array of pointers
The above figure shows the array of pointers used to store the character arrays.
The pointers hold the address of each of the string. Each pointer will point to the first
character of their respective strings.
❖ Pointer to a Pointer
Just as we have pointers to int, float or char, we can also have pointers to pointers.
This is because, a pointer is also a variable. Hence, we can always have another
variable (pointer) which can contain the address of the pointer variable.
EX:
int a = 10; // integer variable
int *p; // pointer to an integer
int **q; // pointer to a pointer to an integer
p = &a;
q = &p;
This is pictorially as shown below.
The above shows a 2-level indirection, however, there is no limit as to how many
levels of indirection we can use.
Here,
void main()
{
int x,y,*big;
printf(“Enter the value of x & y\n”);
scanf(“%d%d”,&x,&y);
big=largest(&x,&y);
printf(“Maximum(%d,%d)=%d\n”,x,y,*big);
}
int *largest(int *a, int *b)
{
if (*a>*b)
return a;
else
return b;
}
Compatibility and void pointer
✔ As we convert the type of one data variable into type of another data variable
using type casting.
✔ We can make an assignment between incompatible pointer types using explicit
type casting.
int a; int a;
float *x float *x;
X=&a; /* error */ /* type casting a pointer */
X=(float *) &a; /*valid */
Void pointer:
Example:
void *p;
void main()
{
int x=10;
double y=3.14156;
void *p;
p=&x;
printf(“x=%d\n”,*((int *)p));
}
✔ An object that occurs on the left hand side of assignment operator is called
L-value.
✔ Anything that occur on the right hand side of assignment statement is called
R-value.
❖ Pointer Expressions:-
Example:
declared and initialized pointer.
y=*p1 * *p2;
sum=sum + *p1;
z=5* - * p2/*p1;
*p2 = *p2 + 10;
*(*(a+i)+j) or *(*(p+i)j)
g o o d
str
printf(“%s”, str); //puts(str);
Write a program using pointer to determine the length of a character string.
main()
{
char *name;
int length;
char *cptr = name;
name = DELHI”;
printf(“%s\n”,name);
❖ Pointer to functions
✔ Once a pointer points to a function, the function can be invoked using this pointer
10 and 15
The sum is 25
❖ Pointers and Structures
✔ The name of an array stands for the address of its zeroth element.
✔ The same thing is true of the name of arrays of structure variables.
✔ Suppose product is an array variable of struct type.
✔ The name product represents the address of its zeroth element.
Consider the following declaration:
struct inventory
{
char name[30];
int number[30];
float price;
}product[2],*ptr;
ptr=product;
struct invent
{
char name[30];
int number[30];
float price;
};
main()
{
struct invent product[3],*ptr;
printf(“INPUT \n\n”);
for(ptr=product;ptr<product+3;ptr++)
scanf(“%s%d%f”,ptrname,&ptrnumber,&ptrprice);
Arrays can be used to represent a group of data items that belong to the same type
such as int or float. But, arrays cannot be used if we want to represent a collection of
data items of different types using a single name.
DEFINING A STRUCTURE
Structure are collection of different data type grouped together under a single
variable name for convenient handling.
'struct' is a keyword, struct type is a name which identifies the structure.
syntax :
struct<structure name or tag name >
{
datatype member 1;
datatype member 2;
};
In defining the structure:
✔ The template is terminated with semicolon.
✔ Entire definition is considered as statement ,each member is declared
independently for its name and type in sepearate statement inside the template.
✔ the tag name can be used to declare structure varaible of its type,later in the
program.
✔ Example:Consider a book database consisting of book name,author,number of
pages,and price.
Arrays Structures
Behaves like built-in data ty Design and declare a data structure before the variables of
pe that type are declared and used
Structure declaration:
A structure can be declared using three different ways as shown below.
✔ Tagged Structures
✔ Structure without tag
✔ Type defined structures
● Tagged structure:
syntax Example
The complete structure definition along with structure declaration is shown below:
struct student
syntax Example
struct struct
{ {
type member1; char name[10];
type member2; int usn_number;
..……. float average_marks;
} cse,ise;
} v1,v2…..vn;
syntax Example
type def struct Type def struct
{ {
type member1; char name[10];
type member2; int usn_number;
..……. float average_marks;
} TYPE_ID; } STUDENT;
The complete structure definition along with typedef definition and declaration
typedef struct
{
char name[10];
int usn_number;
float average_marks;
} STUDENT;
STUDENT cse,ise; /*Structure declaration */
Structure initialization:
The syntax is shown below :
struct tag_name variable = { v1, v2,…vn};
“struct tag_name” is derived data type.
v1,v2..vn are all initial values.
These values are called initializers.
The structure definition, declaration and initialization
OR
struct employee
{ struct employee
Char name[20]; {
Int salary; char name[10];
Int id; int salary;
} a={“Shiva”,10950,2001}; Int id;
};
Struct employee a={“Shiva”,10950,2001};
Syntax: variable.member
struct employee
{
char name[10];
float salary;
int id;
};
struct employee a={“Shiva”,10950,2001};
We can read the name of an employee the salary and id as shown below:
gets(a.name);
scanf(“%f”,&a.salary);
Scanf(“%d”,&a.id);
The various members of a structure can be accessed and printed as shown below:
printf(“%s”,a.name);
printf(“%d”,a.salary);
printf(“%d”,a.id);
⮚ Define a structure type, struct personal that would contain person name,
date of joining and salary, write a program to read this information from the
keyboard and print the same on the screen.
struct personal
{
char name[20];
int day;
char month[10];
main()
{
struct personal person;
printf(“ Input Values\n”);
scanf(“%s%d%s%d%f”,person.name,&person.day,person.month,&person.year,&pers
on.salary);
printf(“%s%d%s%d%f”,person.name,person.day,person.month,person.year,person.sal
ary);
}
⮚ Sizeof a structure(Concept of Slack Bytes)
The size of a structure is defined as the sum of sizes of each members of the
structures.
struct student
{
char name[10];
int roll_number;
double avg_marks;
}a;
If 2000 is the starting address of the variable a,then the starting address of each
member depends on sum of sizes of previous members.
Some times,the size of the structure will not be equal to sum of sizes of the individual
members .
This is because of slack bytes.
0 1 2 3
-char- Slack byte --------int---------
A character data takes one byte and an integer takes two bytes.
One byte between them is left unoccupied.
This unoccupied byte is known as the slack byte.
❖ Structure Operation:
person1 = person2;
person2 = person1;
person1 == person2;
person2 != person1;
The members of two structure variables of same type can be compared using
relational operators.
a.member1==b.member2
a.member1!=b.member2
typedef struct
{
char name[10];
int usn_number;
float average_marks;
}STUDENT;
void main()
{
STUDENT a;
STUDENT *p;
P=&a;
}
Using this pointer various members of the structure can be accessed using two
methods:
If P is pointer to a structure, then the structure itself can be accessed using indirection
operator as shown below.
Once the structure is accessed, each members of the structure can be accessed using
dot operator.
(*p).name;
(*p).roll_number;
(*p).average_marks
Pname
Proll_number
Paverage_marks
⮚ Complex Structures:
✔ Nested structures
✔ Structure containing arrays
✔ Structure containing pointers
✔ Arrays of structure
⮚ Nested structures
A structure which includes another structure is called nested structure i.e, structure
can be used as a member of another structure.
✔ A single or multi_dimensional array of int, float, char and double can be used
within the structures.
typedef struct
{ d.day=“Thursday”;
}DATE;
DATE d;
❖ Array of Structures
As we have an array of integers, we can have an array of structures also.
Example:Suppose we want to store the information of 10 students consisting of
name,marks and year of passing.
typedef struct
To store the information of more number of students,we can have the following
declaration.
STUDENT a[10];
LAB PROGRAM 13. Implement structures to read, write and compute average-
marks and the students scoring
above and below the average marks for a class of N students.
#include<stdio.h>
struct student
{
char name[20];
int rollno;
int m1, m2, m3;
int avg;
};
main( )
{
struct student s[100];
int n, i, sum=0, class_avg =0;
printf("Enter the number of students\n");
scanf("%d", &n);
// To read the details of 'n' students
printf("Enter the student details\n");
for(i=0; i<n; i++)
{
printf("Enter the name\n");
scanf("%s", s[i]. name);
Syntax :
union tag_name
{
type1 member 1;
type2 member 2;
……
};
Consider the following definition and declaration :
typedef union
{
int i;
double d; Union definition
char c;
union item
{
int i;
double d;
char c;
}x;
By using the dot operator(.) we can access various members of the union.
x.i;
x.d;
x.c;
X->i OR (*x).i
x->d OR (*x).d
X->c OR (*x).c
Memory representation of Union:
union item
{
int m;
float x;
char c.;
#include<stdio.h>
void main()
{
typedef union
{
int marks;
char grade;
float percentage;
}STUDENT;
STUDENT x;
x.marks=100;
printf(“Marks=%d\n”,x.marks);
x.grade=‘A’;
printf(“Grade = %c\n”,x.grade);
x.percentage=99.5;
printf(“percentage = %f\n”,x.percentage);
}
❖ Preprocessors
The preprocessing statements also called preprocessor directive starts with symbol ‘#’
in C language.
The preprocessor directives are lines included in our programs that starts with
character #.
Symbolic name can be defined using #define directive whereas already defined
symbolic names can be undefined using #undef.
#define PI 3.146
#undef PI
⮚ Macros
#include<stdio.h>
#define SQUARE(x) (x*x)
void main()
{
int m,n;
n=5;
m=10;
printf(“ 5 square =%d\n”,SQUARE(n));
` printf(“ 10 square =%d\n”,SQUARE(m));
printf(“ 10+5 square =%d\n”,SQUARE(m+n));
}
O/P: 5 square=25
10 square=100
/* Program to find largest of two numbers using macro */
#include<stdio.h>
#define MAX(x,y)((x)>(y)?(x):(y))
int a,b,c;
printf(“ Enter two number\n”);
` scanf(“%d%d”,&a,&b);
c=MAX(a,b);
printf(“ Maximum =%d\n”,c);
}
⮚ Nesting of macros:
we can also use one macro in the definition of another macro.
#define M 5
#define N M+1
#define square(x) ((x)*(x))
#define CUBE(x) (square(x)*x)
#define SIXTH(x) (CUBE(x)*CUBE(x))
⮚ File inclusion:
This is the process of inserting external files containg macros and function into the C
program.
#include<stdio.h> File:factor.h
#include “factor.h”
Int fact(int n)
main() {
{ int f=1;
int number, f; If(n==0)
printf(“Enter the number\n”);
scanf(“%d”,&number); return(1);
f=fact(number);
else
printf(“Factorial of %d=%d\n”,number,f)
} return(n*fact(n-1))
⮚ Conditional Compilation:
#ifdef /* if defined */
#elif /* else if */
#endif
#else
#undef /* undefined */
#if
#pragma
#error
Example:
main()
{
#ifdef VER1
code for version1
#else
code for version2
}
To run the first version version1.
Then #define the following statement before the main()
If Directive
main() #else
{ {
--- Statement 21;
-- Statement 21;
#if TEST<=4 .
{ .
Statement 11; Statement 2n;
Statement 12; }
.
Statementn; #endif
} }