0% found this document useful (0 votes)
14 views21 pages

Pointer Class XII

Uploaded by

abxrnt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views21 pages

Pointer Class XII

Uploaded by

abxrnt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

1

Class XII
Sub: Computer Science & Application (CSCA)
Chapter 8 (Pointer)
Pointer

Pointers are symbolic representations of addresses. They enable programs


to simulate call-by-reference as well as to create and manipulate dynamic
data structures. Iterating over elements in arrays or other data structures
is one of the main use of pointers.
The address of the variable you’re working with is assigned to the pointer
variable that points to the same data type (such as an int or string).
Syntax:
datatype *var_name;
int *ptr; // ptr can point to an address which holds int data

How to use a pointer?


 Define a pointer variable
 Assigning the address of a variable to a pointer using the unary
operator (&) which returns the address of that variable.
 Accessing the value stored in the address using unary operator (*)
which returns the value of the variable located at the address specified
by its operand.
The reason we associate data type with a pointer is that it knows how
many bytes the data is stored in. When we increment a pointer, we
increase the pointer by the size of the data type to which it points.

// C++ program to illustrate Pointers


#include <bits/stdc++.h>
using namespace std;
void geeks()
{
int var = 20;

// declare pointer variable


int* ptr;

// note that data type of ptr and var must be same


ptr = &var;
2

// assign the address of a variable to a pointer


cout << "Value at ptr = " << ptr << "\n";
cout << "Value at var = " << var << "\n";
cout << "Value at *ptr = " << *ptr << "\n";
}
// Driver program
int main()
{
geeks();
return 0;
}

Output
Value at ptr = 0x7ffe454c08cc
Value at var = 20
Value at *ptr = 20

References and Pointers


There are 3 ways to pass C++ arguments to a function:
 Call-By-Value
 Call-By-Reference with a Pointer Argument
 Call-By-Reference with a Reference Argument

// C++ program to illustrate call-by-methods

#include <bits/stdc++.h>
using namespace std;

// Pass-by-Value
int square1(int n)
{
// Address of n in square1() is not the same as n1 in
// main()
cout << "address of n1 in square1(): " << &n << "\n";

// clone modified inside the function


n *= n;
return n;
}
// Pass-by-Reference with Pointer Arguments
void square2(int* n)
{
3

// Address of n in square2() is the same as n2 in main()


cout << "address of n2 in square2(): " << n << "\n";

// Explicit de-referencing to get the value pointed-to


*n *= *n;
}
// Pass-by-Reference with Reference Arguments
void square3(int& n)
{
// Address of n in square3() is the same as n3 in main()
cout << "address of n3 in square3(): " << &n << "\n";

// Implicit de-referencing (without '*')


n *= n;
}
void geeks()
{
// Call-by-Value
int n1 = 8;
cout << "address of n1 in main(): " << &n1 << "\n";
cout << "Square of n1: " << square1(n1) << "\n";
cout << "No change in n1: " << n1 << "\n";

// Call-by-Reference with Pointer Arguments


int n2 = 8;
cout << "address of n2 in main(): " << &n2 << "\n";
square2(&n2);
cout << "Square of n2: " << n2 << "\n";
cout << "Change reflected in n2: " << n2 << "\n";

// Call-by-Reference with Reference Arguments


int n3 = 8;
cout << "address of n3 in main(): " << &n3 << "\n";
square3(n3);
cout << "Square of n3: " << n3 << "\n";
cout << "Change reflected in n3: " << n3 << "\n";
}
// Driver program
int main() { geeks(); }
Output
address of n1 in main(): 0x7fffa7e2de64
address of n1 in square1(): 0x7fffa7e2de4c
Square of n1: 64
No change in n1: 8
address of n2 in main(): 0x7fffa7e2de68
4

address of n2 in square2(): 0x7fffa7e2de68


Square of n2: 64
Change reflected in n2: 64
address of n3 in main(): 0x7fffa7e2de6c
address of n3 in square3(): 0x7fffa7e2de6c
Square of n3: 64
Change reflected in n3: 64

In C++, by default arguments are passed by value and the changes made in the
called function will not reflect in the passed variable. The changes are made into a
clone made by the called function. If wish to modify the original copy directly
(especially in passing huge object or array) and/or avoid the overhead of cloning,
we use pass-by-reference. Pass-by-Reference with Reference Arguments does not
require any clumsy syntax for referencing and dereferencing.
 Function pointers in C
 Pointer to a Function
Array Name as Pointers
An array name contains the address of the first element of the array which acts like
a constant pointer. It means, the address stored in the array name can’t be
changed. For example, if we have an array named val then val and &val[0] can be
used interchangeably.
C++

// C++ program to illustrate Array Name as Pointers

#include <bits/stdc++.h>

using namespace std;

void geeks()

{
5

// Declare an array

int val[3] = { 5, 10, 20 };

// declare pointer variable

int* ptr;

// Assign the address of val[0] to ptr

// We can use ptr=&val[0];(both are same)

ptr = val;

cout << "Elements of the array are: ";

cout << ptr[0] << " " << ptr[1] << " " << ptr[2];

// Driver program

int main() { geeks(); }

Output
Elements of the array are: 5 10 20
6

If pointer ptr is sent to a function as an argument, the array val can be


accessed in a similar fashion. Pointer vs Array

Pointer Expressions and Pointer Arithmetic


A limited set of arithmetic operations can be performed on pointers which
are:
 incremented ( ++ )
 decremented ( — )
 an integer may be added to a pointer ( + or += )
 an integer may be subtracted from a pointer ( – or -= )
 difference between two pointers (p1-p2)

Pointers and String literals


String literals are arrays containing null-terminated character sequences.
String literals are arrays of type character plus terminating null-character,
with each of the elements being of type const char (as characters of string
can’t be modified).
This declares an array with the literal representation for “geek”, and then
a pointer to its first element is assigned to ptr. If we imagine that “geek” is
stored at the memory locations that start at address 1800, we can
represent the previous declaration as:

As pointers and arrays behave in the same way in expressions, ptr can be
used to access the characters of a string literal. For example:
char x = *(ptr+3);
char y = ptr[3];

Here, both x and y contain k stored at 1803 (1800+3).

Pointers to pointers
In C++, we can create a pointer to a pointer that in turn may point to data
or another pointer. The syntax simply requires the unary operator (*) for
each level of indirection while declaring the pointer.
char a;
char *b;
7

char ** c;
a = ’g’;
b = &a;
c = &b;

Here b points to a char that stores ‘g’ and c points to the pointer b.

Void Pointers
This is a special type of pointer available in C++ which represents the
absence of type. Void pointers are pointers that point to a value that has
no type (and thus also an undetermined length and undetermined
dereferencing properties). This means that void pointers have great
flexibility as they can point to any data type. There is a payoff for this
flexibility. These pointers cannot be directly dereferenced. They have to
be first transformed into some other pointer type that points to a
concrete data type before being dereferenced.

// C++ program to illustrate Void Pointer

#include <bits/stdc++.h>
using namespace std;
void increase(void* data, int ptrsize)
{
if (ptrsize == sizeof(char)) {
char* ptrchar;

// Typecast data to a char pointer


ptrchar = (char*)data;

// Increase the char stored at *ptrchar by 1


(*ptrchar)++;
cout << "*data points to a char"
<< "\n";
}
else if (ptrsize == sizeof(int)) {
int* ptrint;

// Typecast data to a int pointer


ptrint = (int*)data;

// Increase the int stored at *ptrchar by 1


(*ptrint)++;
cout << "*data points to an int"
<< "\n";
}
}
void geek()
8

{
// Declare a character
char c = 'x';

// Declare an integer
int i = 10;

// Call increase function using a char and int address


// respectively
increase(&c, sizeof(c));
cout << "The new value of c is: " << c << "\n";
increase(&i, sizeof(i));
cout << "The new value of i is: " << i << "\n";
}
// Driver program
int main() { geek(); }

Output
*data points to a char
The new value of c is: y
*data points to an int
The new value of i is: 11

Invalid pointers
A pointer should point to a valid address but not necessarily to valid
elements (like for arrays). These are called invalid pointers. Uninitialized
pointers are also invalid pointers.
int *ptr1;
int arr[10];
int *ptr2 = arr+20;

Here, ptr1 is uninitialized so it becomes an invalid pointer and ptr2 is out


of bounds of arr so it also becomes an invalid pointer. (Note: invalid
pointers do not necessarily raise compile errors)

NULL Pointers
A null pointer is a pointer that point nowhere and not just an invalid
address. Following are 2 methods to assign a pointer as NULL;
int *ptr1 = 0;
int *ptr2 = NULL;

Advantages of Pointers
9

 Pointers reduce the code and improve performance. They are used to
retrieve strings, trees, arrays, structures, and functions.
 Pointers allow us to return multiple values from functions.
 In addition to this, pointers allow us to access a memory location in the
computer’s memory.

S.No Static Memory Allocation Dynamic Memory Allocation

In the static memory allocation,


variables get allocated In the Dynamic memory allocation,
permanently, till the program variables get allocated only if your
1 executes or function call finishes. program unit gets active.

Static Memory Allocation is done Dynamic Memory Allocation is done


2 before program execution. during program execution.

It uses stack for managing the static It uses heap for managing the dynamic
3 allocation of memory allocation of memory

4 It is less efficient It is more efficient

In Dynamic Memory Allocation, there is


In Static Memory Allocation, there memory re-usability and memory can be
5 is no memory re-usability freed when not required

In static memory allocation, once In dynamic memory allocation, when


the memory is allocated, the memory is allocated the memory size can
6 memory size can not change. be changed.

This allows reusing the memory. The user


In this memory allocation scheme, can allocate more memory when
we cannot reuse the unused required. Also, the user can release the
7 memory. memory when the user needs it.
10

In this memory allocation scheme, In this memory allocation scheme,


execution is faster than dynamic execution is slower than static memory
8 memory allocation. allocation.

In this memory is allocated at


9 compile time. In this memory is allocated at run time.

In this allocated memory remains In this allocated memory can be released


10 from start to end of the program. at any time during the program.

Example: This static memory


allocation is generally used Example: This dynamic memory
11 for array. allocation is generally used for linked list.

Free Store is a pool of unallocated heap memory given to a program that is used
by the program for dynamic allocation during the execution of program.

Every program is provided with a pool of unallocated heap memory that it may
utilize during the execution. This pool of available memory is referred to as free
store of the program.

The allocated free store memory is unnamed. Objects allocated on the free store
are manipulated indirectly through pointers. Another aspect of free store is that
the allocated memory is uninitialized. The programmer is responsible for
initializing it explicitly.

The free store memory is allocated through the use of new operator and
deallocated through delete operator.

Free store memory (dynamically) allocated during run-time and static memory
allocation takes place during compile-time. An object's life time i.e., as long as the
object remains in the memory during the program execution, is known as an
object's extend. Global variables or the variables having file scope are spoken of
as having static extent. That means, the storage is allocated to them before the
program's start-up and remains bound to the variable throughout the program
execution.
11

Variables having local scope are spoken of having local extend. Storage is
allocated to them at each entry into the local scope (i.e., as soon as their local
scope starts); and on exit (from the local scope), the storage is freed up. A local
variable with static specifier has static extend.

Declaration and initialization of pointer C++

The general form of a pointer declaration is as follows :

type ∗var_name ;

where type is any valid C++ data type and var_name is the name of the pointer
variable. Following declarations declares pointers of different types :

int ∗iptr ; //creates an integer pointer iptr


char ∗cptr ; //creates a character pointer cptr
float ∗fptr ; //creates a float pointer fptr

When we say that iptr is an integer pointer, it means that the memory location
being pointer to by iptr can hold only integer values. In other words, it can stated
that iptr is a pointer to integer. Similarly, in the above given declarations, cptr is a
pointer to a character and fptr is a pointer to a floating-point value. Thus, it is the
base type of the pointer that defines what types of variables the pointer can point
to. Technically, any type of pointer can point anywhere in memory.

However, all pointer arithmetic is done relative to its base type, so it is important
to declare the pointers correctly.

Two special operators ∗ and & are used with pointers. The & is a unary operator
that returns the memory address of its operand. For example,

int i = 25 ; // declares an int variable i


int ∗iptr ; // declares an int pointer iptr
iptr = &i ; // stores the memory address of i into iptr

The above given assignment statement stores the memory address of i (& returns
memory address of its operand) into iptr so that iptr is now pointing to the
memory location of i. The expression &i will return an int pointer value because i
is an integer thus, &i will return a pointer to integer. Similarly, if ch is a character
variable, then &ch will return a char pointer value.

C++ Pointers Initialization


12

Attention - A pointer variable must not remain uninitialized since uninitialized


pointers cause the system crash. Even if you do not have any legal pointer value
to initialize a pointer, you can initialize it with NULL pointer value.

Assigning NULL to a pointer initializes it to a value which is not a legal pointer but
it saves you from the 'Big' problem of uninitialized pointers. A program can later
test a pointer against NULL (the zero pointer) to see whether it contains a legal
pointer or not. For example, consider the following code fragment :

int ∗iptr = NULL ; //iptr gets initialized but does not to a legal address
:
if(iptr != NULL)
{
: //use the pointer if it pointers to a legal address
}

The expression (iptr != NULL) is equivalent to expression (iptr).

The zero pointer NULL is defined in the standard file stddef.h.

When you use NULL for initializing pointers then before using the pointer
anywhere in the program, first check that it is non-zero or non-NULL as shown in
the above code fragment.

nullptr in C++

In C++, a new keyword namely nullptr has been introduced, which is a


distinguished null-point constant. So, now on (provided compiler implements C++
standard), you can initialize your pointers with nullptr, e.g.,

char ∗cptr = nullptr ;


int ∗iptr = nullptr ;

Difference between NULL and nullptr

Difference between NULL and nullptr are:

 NULL is not defined by C++, it is programmer or compiler-defined whereas


nullptr has been defined by C++ as a legal null pointer
 NULL is internally mapped to int 0(zero) whereas nullptr is a legal
empty/null pointer, which is implicitly convertible and comparable to any
pointer-type. This feature has another benefit too. Until now if you had two
overloaded functions.

Here are examples demonstrating the difference between NULL and nullptr

int f1(char∗) ;
13

int f1(int) ;

And if you have a pointer as

char ∗cptr = NULL ;

then a function call f1(cptr) would always map to f1(int) and not to f1(char ∗)
because internally NULL maps to an int. But with nullptr i.e.,

char ∗cptr = nullptr ;

function call f1(cptr) will map to f1(char∗) only.

C++ Pointer Arithmetic


Only two arithmetic operation, addition and subtraction, may be performed on
pointers. When you add 1 to a pointer, you are actually adding the size of
whatever the pointer is pointing at. That is, each time a pointer is incremented by
1, it points to the memory location of the next element of its base type. To
understand it more clearly, let us take an example. Let iptr be an integer pointer,
currently pointing to memory address 1001. Assuming that the int size is 2 bytes,
then after the following expression

iptr++ ;

iptr will be pointing to 1003, not to 1002. Each time you increment iptr by 1, it will
point to the next integer. Similarly, when you decrement iptr by 1 it will point to
the location of the previous element of its base type (int here) which is at address
999.

Dereferencing: Dereferencing refers to changing/accessing state of the pointer.

Dereferencing is used to access or manipulate data contained in memory location


pointed to by a pointer. *(asterisk) is used with pointer variable when
dereferencing the pointer variable, it refers to variable being pointed, so this is
called dereferencing of pointers.
int main() {
int a = 7, b ;
int *p; // Un-initialized Pointer
p = &a; // Stores address of a in ptr
b = *p; // Put Value at ptr in b
}
14

Here, address in p is basically address of a variable.

Dynamic Allocation Operators

Check Textbook

Creating Dynamic Array

Check Textbook

The new operator and 2-D arrays

Check Textbook

Memory Leaks

Memory leakage occurs in C++ when programmers allocates memory by


using new keyword and forgets to deallocate the memory by using
delete() function or delete[] operator. One of the most memory leakage
occurs in C++ by using wrong delete operator.
The delete operator should be used to free a single allocated memory
space, whereas the delete [] operator should be used to free an array of
data values.
Disadvantage with memory leakage:
If a program has memory leaks, then its memory usage is satirically
increasing since all systems have limited amount of memory and memory
is costly. Hence it will create problems.
Reasons for Memory Leak
Check Textbook
Pointer and Arrays
In C++, Pointers are variables that hold addresses of other variables. Not
only can a pointer store the address of a single variable, it can also store
the address of cells of an array.
Consider this example:

int *ptr;
int arr[5];
15

// store the address of the first


// element of arr in ptr
ptr = arr;

Here, ptr is a pointer variable while arr is an int array. The code ptr =
arr; stores the address of the first element of the array in variable ptr .
Notice that we have used arr instead of &arr[0] . This is because both are
the same. So, the code below is the same as the code above.
int *ptr;
int arr[5];
ptr = &arr[0];

The addresses for the rest of the array elements are given
by &arr[1] , &arr[2] , &arr[3] , and &arr[4] .

Array of Pointers
Check Textbook

Pointer and Const

Pointer and Strings

Check Textbook

Pointer and Functions

The call by pointer method of passing arguments to a function copies the address
of an argument into the formal parameter. Inside the function, the address is
used to access the actual argument used in the call. This means that changes
made to the parameter affect the passed argument.
To pass the value by pointer, argument pointers are passed to the functions just
like any other value. So accordingly you need to declare the function parameters
as pointer types as in the following function swap(), which exchanges the values
of the two integer variables pointed to by its arguments.
// function definition to swap the values.
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */

return;
16

Invoking Functions by Passing the references

ass-by-reference means to pass the reference of an argument in the calling


function to the corresponding formal parameter of the called function. The called
function can modify the value of the argument by using its reference passed in.

The following example shows how arguments are passed by reference. The
reference parameters are initialized with the actual arguments when the function
is called.

#include <stdio.h>

void swapnum(int &i, int &j) {


int temp = i;
i = j;
j = temp;
}

int main(void) {
int a = 10;
int b = 20;

swapnum(a, b);
printf("A is %d and B is %d\n", a, b);
return 0;
}
When the function swapnum() is called, the values of the variables a and b are
exchanged because they are passed by reference. The output is:
A is 20 and B is 10
To modify a reference that is qualified by the const qualifier, you must cast
away its constness with the const_cast operator. For example:
#include <iostream>
using namespace std;

void f(const int& x) {


int& y = const_cast<int&>(x);
++y;
}

int main() {
int a = 5;
f(a);
cout << a << endl;
}
This example outputs 6.

Pass-by-references is more efficient than pass-by-value, because it does not copy


the arguments. The formal parameter is an alias for the argument. When the
17

called function read or write the formal parameter, it is actually read or write the
argument itself.

The difference between pass-by-reference and pass-by-value is that modifications


made to arguments passed in by reference in the called function have effect in
the calling function, whereas modifications made to arguments passed in by value
in the called function can not affect the calling function. Use pass-by-reference if
you want to modify the argument value in the calling function. Otherwise, use
pass-by-value to pass arguments.

The difference between pass-by-reference and pass-by-pointer is that pointers


can be NULL or reassigned whereas references cannot. Use pass-by-pointer
if NULL is a valid parameter value or if you want to reassign the pointer.
Otherwise, use constant or non-constant references to pass arguments.

Functions Returning Pointers

Instead of a regular value or even a reference, a function can return a pointer.


You can start to specify this by typing the * operator on the left side of the
function's name. Here is an example:

double * GetSalary()
{

Then, use the body of the function to define it. Before the closing curly bracket of
the function, remember to return a pointer to the return value. Here is an
example:

double * GetSalary()
{
double salary = 26.48;

double *HourlySalary = &salary;

return HourlySalary;

Because a pointer by defining is a reference to the address where a variable


resides, when a function is defined as returning a pointer, you can also return a
reference to the appropriate type. Here is an example:

double * GetSalary()
{
double salary = 26.48;
18

return &salary;
}

After defining the function, you can call it. Remember that the asterisk is used to
get the value of a pointer. This means that, when calling the function, if you want
to access its value, make sure you include the asterisk on the left side of the name
of the function.

Pointers and Structures

A pointer variable can be created not only for native types like
( int , float , double etc.) but they can also be created for user defined types
like structure.
If you do not know what pointers are, visit C++ pointers.
Here is how you can create pointer for structures:

#include <iostream>
using namespace std;

struct temp {
int i;
float f;
};

int main() {
temp *ptr;
return 0;
}

This program creates a pointer ptr of type structure temp .

Example: Pointers to Structure

#include <iostream>
using namespace std;

struct Distance {
int feet;
float inch;
};

int main() {
Distance *ptr, d;
19

ptr = &d;

cout << "Enter feet: ";


cin >> (*ptr).feet;
cout << "Enter inch: ";
cin >> (*ptr).inch;

cout << "Displaying information." << endl;


cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";

return 0;
}

Output
Enter feet: 4
Enter inch: 3.5
Displaying information.
Distance = 4 feet 3.5 inches

In this program, a pointer variable ptr and normal variable d of type


structure Distance is defined.
The address of variable d is stored to pointer variable, that is, ptr is
pointing to variable d . Then, the member function of variable d is
accessed using pointer.

Self Referencial Structures

Self Referential structures are those structures that have one or more
pointers which point to the same type of structure, as their member.

In other words, structures pointing to the same type of structures are self-
referential in nature
20

Types of Self Referential Structures


1. Self Referential Structure with Single Link
2. Self Referential Structure with Multiple Links

Dynamic Structures

Check Textbook

Objects as function arguments

In C++ we can pass class’s objects as arguments and also return them from
a function the same way we pass and return other variables. No special
keyword or header file is required to do so.

Passing an Object as argument

To pass an object as an argument we write the object name as the


argument while calling the function the same way we do it for other
variables.
Syntax:
function_name(object_name);

Example: In this Example there is a class which has an integer variable ‘a’
and a function ‘add’ which takes an object as argument. The function is
called by one object and takes another as an argument. Inside the
function, the integer value of the argument object is added to that on
which the ‘add’ function is called. In this method, we can pass objects as
an argument and alter them.

Passing Objects through reference

Pass-by-reference means to pass the reference of an argument in the calling


function to the corresponding formal parameter of the called function. The called
function can modify the value of the argument by using its reference passed in.

The following example shows how arguments are passed by reference. The
reference parameters are initialized with the actual arguments when the function
is called.

#include <stdio.h>

void swapnum(int &i, int &j) {


21

int temp = i;
i = j;
j = temp;
}

int main(void) {
int a = 10;
int b = 20;

swapnum(a, b);
printf("A is %d and B is %d\n", a, b);
return 0;
}
When the function swapnum() is called, the values of the variables a and b are
exchanged because they are passed by reference. The output is:
A is 20 and B is 10

The this pointer

The this pointer is a pointer accessible only within the nonstatic member functions
of a class, struct, or union type. It points to the object for which the member
function is called. Static member functions don't have a this pointer.

Syntax
this
this->member-identifier

You might also like