Pointer Class XII
Pointer Class XII
Class XII
Sub: Computer Science & Application (CSCA)
Chapter 8 (Pointer)
Pointer
Output
Value at ptr = 0x7ffe454c08cc
Value at var = 20
Value at *ptr = 20
#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";
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++
#include <bits/stdc++.h>
void geeks()
{
5
// Declare an array
int* ptr;
ptr = val;
cout << ptr[0] << " " << ptr[1] << " " << ptr[2];
// Driver program
Output
Elements of the array are: 5 10 20
6
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];
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.
#include <bits/stdc++.h>
using namespace std;
void increase(void* data, int ptrsize)
{
if (ptrsize == sizeof(char)) {
char* ptrchar;
{
// Declare a character
char c = 'x';
// Declare an integer
int i = 10;
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;
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.
It uses stack for managing the static It uses heap for managing the dynamic
3 allocation of memory allocation of memory
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.
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 :
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,
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.
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
}
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++
Here are examples demonstrating the difference between NULL and nullptr
int f1(char∗) ;
13
int f1(int) ;
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.,
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.
Check Textbook
Check Textbook
Check Textbook
Memory Leaks
int *ptr;
int arr[5];
15
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
Check Textbook
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
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>
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;
int main() {
int a = 5;
f(a);
cout << a << endl;
}
This example outputs 6.
called function read or write the formal parameter, it is actually read or write the
argument itself.
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;
return HourlySalary;
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.
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;
}
#include <iostream>
using namespace std;
struct Distance {
int feet;
float inch;
};
int main() {
Distance *ptr, d;
19
ptr = &d;
return 0;
}
Output
Enter feet: 4
Enter inch: 3.5
Displaying information.
Distance = 4 feet 3.5 inches
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
Dynamic Structures
Check Textbook
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.
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.
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>
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 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