0% found this document useful (0 votes)
10 views

lecture_7(pointers)[1]

The document provides an overview of pointers, including their declaration, manipulation, and the use of dynamic variables in C++. It explains the differences between static and dynamic arrays, memory allocation with 'new' and 'delete', and how pointers can be passed to functions. Additionally, it covers the 'this' pointer in class member functions and provides examples of pointer operations and their implications in C++ programming.

Uploaded by

ihsanyousaf09
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

lecture_7(pointers)[1]

The document provides an overview of pointers, including their declaration, manipulation, and the use of dynamic variables in C++. It explains the differences between static and dynamic arrays, memory allocation with 'new' and 'delete', and how pointers can be passed to functions. Additionally, it covers the 'this' pointer in class member functions and provides examples of pointer operations and their implications in C++ programming.

Uploaded by

ihsanyousaf09
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

POINTERS

Classes, Structs, and Pointer


Variables:
Pointer variable:
• A variable whose content is an address (that is, a memory address)
and is therefore said to point to a memory address .
• The value of a pointer variable is an address or memory space that
typically contains some data.
• Therefore, when you declare a pointer variable, you also specify the
data type of the value to be stored in the memory location pointed to
by the pointer variable.
The general syntax to declare a pointer
variable is :
dataType *identifier;
char *ch;

As an example, consider the following statements:


int *p; or int* p; or int * p;

the character * can appear anywhere between the data type name and the
variable name.
Consider the following statements:

1. num = 78;
2. p = #
3. *p = 24;
#INCLUDE<IOSTREAM>
The following shows the values of the variables after the
execution of each statement
1. A declaration such as int *p; allocates memory for p only,
not for *p.
2. The content of p points only to a memory location of type int.
3. &p, p, and *p all have different meanings.
4. &p means the address of p—that is, 1200
5. p means the content of p, which is 1800, after the statement
p = &num; executes.
6. *p means the content of the memory location to which p points.
after the statement p = &num; executes, the value of *p is 78;
after the statement *p = 24; executes, the value of *p is 24
Example:
Consider the following statements:
int *p;
int x;
The values of &p, p, *p, &x, and x are as follows:

&p 1400
p ? (unknown)
*p Does not exist (undefined)
&x 1750
x ? (unknown)
Suppose that the following statements are executed in the order given:
x = 50;
p = &x;
*p = 38;

After the statement x = 50; executes, the values of &p, p, *p, &x, and x are as
follows:
&p 1400
p ? (unknown)
*p Does not exist (undefined)
&x 1750
x 50
• After the statement p = &x; executes,
the values of &p, p, *p, &x, and x are as follows:

&p 1400
p 1750
*p 50
&x 1750
x 50
• After the statement *p = 38; executes, the values of &p, p, *p, &x, and
x are as follows:
(Because *p and x refer to the same memory space, the value of x is
also changed to 38.)
&p 1400
p 1750
*p 38
&x 1750
x 38
How to declare and manipulate pointers
to classes and structs:
• Both classes and structs have the same capabilities.
• The only difference between classes and structs is that, by default, all
members of a class are private, and by default, all members of a struct
are public
Consider the following declaration of a struct:
struct studentType
{
char name[26];
double gpa;
int sID;
char grade;
};

studentType student;
studentType* studentPtr;
student is an object of type studentType, and

studentPtr is a pointer variable of type studentType

studentPtr = &student;

(*studentPtr).gpa = 3.9; //stores 3.9 in gpa of student

In C++, the dot operator, . , has a higher precedence than


the dereferencing operator *.
*studentPtr.gpa // the expression studentPtr.gpa evaluates first.
// would result in a syntax error
C++ provides another operator called the member access operator
arrow, ->

Thus, the statement: (*studentPtr).gpa = 3.9;

is equivalent to the statement: studentPtr->gpa = 3.9;


Dynamic Variables:
• Variables that are created during program execution are called
dynamic variables.
• With the help of pointers, C++ creates dynamic variables.
• allocate and deallocate memory during program execution using
pointers.
• C++ provides two operators, new and delete, to create and destroy
dynamic variables
• When a program requires a new variable, the operator new is used.
• When a program no longer needs a dynamic variable, the operator
delete is used
Operator new :
• The operator new has two forms:
• one to allocate a single variable and another to allocate an array of
variables.
• The syntax to use the operator new is:

new dataType; //to allocate a single variable


new dataType[intExp];

• intExp is any expression evaluating to a positive integer


consider the following statement:

p = new int;

• This statement creates a variable during program execution somewhere in


memory and stores the address of the allocated memory in p.
• The allocated memory is accessed via pointer dereferencing—namely, *p.
the statement

q = new char[16];

• creates an array of 16 components of type char and stores the base


address of the array in q.
• Because a dynamic variable is unnamed, it cannot be accessed
directly. It is accessed indirectly by the pointer returned by new.
int *p; //p is a pointer of type int
char *name; //name is a pointer of type char
string *str; //str is a pointer of type string

p = new int; //allocates memory of type int and stores in p


*p = 28; //stores 28 in the allocated memory
name = new char[5]; //allocates memory for an array of five
strcpy(name, "John");

str = new string; //allocates memory of type string


*str = "Sunny Day";
Operator delete :
Suppose you have the following declaration:
int *p;
This statement declares p to be a pointer variable of type int.
Next, consider the following statements:
p = new int;
*p = 54;
p = new int;
*p = 73;
Following is the effect of these statements.
After execution of the statements
• p points to the new memory space at location 1800. The previous
memory space at location 1500 is now inaccessible.
• In addition, the memory space 1500 remains as marked allocated. In
other words, it cannot be freed or reallocated.
• This is called memory leak. That is, there is an unused memory space
that cannot be allocated.
How to avoid memory leak ?
• When a dynamic variable is no longer needed, it can be
destroyed; that is, its memory can be deallocated.
• The C++ operator delete is used to destroy dynamic
variables.
• The syntax to use the operator delete has two forms:
delete pointerVariable; //to deallocate a single
//dynamic variable
delete [] pointerVariable; //to deallocate a dynamically
//created array
delete p;
delete [] name;
delete str;

• The statements deallocate the memory spaces that the pointers p,


name, and str point to, but only marks the memory spaces that these
pointer variables point to as deallocated.
• After these statements execute, these pointer variables may still
contain the addresses of the deallocated memory spaces.
• One way to avoid this is to set these pointers to nullptr after the
delete operation.
• Also note that for the operator delete to work properly, the pointer
must point to a valid memory space.
Operations on Pointer Variables:
• The operations that are allowed on pointer variables are
the assignment and relational operations and some limited arithmetic
operations.
For example : suppose that we have the following statements:
int *p, *q;
• The statement p = q; copies the value of q into p.
both p and q point to the same memory location.
• Any changes made to *p automatically change the value of *q,
and vice versa .
• Two pointer variables of the same type can be compared for
equality/non equality , and so on.

The expression p == q or p!=q

• Integer values can be added and subtracted from a pointer variable.


The increment operator increments the value of a pointer variable by
the size of the data type or structure to which it is pointing.
Increment/Decrement
• Integer values can be added and subtracted from a pointer variable.
• The increment operator increments the value of a pointer variable by
the size of the data type or structure to which it is pointing.
int *p;
double *q;
char *chPtr;
• the size of the memory allocated for an int variable is 4 bytes, a double
variable is 8 bytes, and a char variable is 1 byte.
The statement p++; or p = p + 1;
increments the value of p by 4 bytes because p is a pointer of type int.
Dynamic Arrays :

Static arrays :
• Static arrays have their size or length determined when the array is
created and/or allocated.
• One of the limitations of a static array is that every time you execute
the program, the size of the array is fixed, so it might not be possible
to use the same array to process different data sets of the same type.
Dynamic Arrays :
• An array created during the execution of a program is called a
dynamic array.
• A dynamic array is quite similar to a regular array, but its size is
modifiable during program runtime
• To create a dynamic array, we use the second form of the new
operator.
• The statement int *p;
declares p to be a pointer variable of type int.
• The statement p = new int[10];
allocates 10 contiguous memory locations, each of type int,
and stores the address of the first memory location into p.
int *p;
p = new int[10];
*p = 25;

stores 25 into the first memory location, and the statements:

p++; //p points to the next array component


*p = 35; //store 35 into the second memory location
• C++ allows us to use array notation to access these memory locations.

For example, the statements


p[0] = 25;
p[1] = 35;

• store 25 and 35 into the first and second array components,


respectively.
• When the array notation is used to process the array pointed to by p,
p stays fixed at the first memory location.
An array name is a constant pointer.
The statement
int list[5];
• declares list to be an array of five components of type int.
• list itself is a variable, and the value stored in list is the base address
of the array that is, the address of the first array component
If p is a pointer variable of type int, then the statement
p = list;
copies the value of list, (which is 1000 for example) the base address
of the array, into p.
the value stored in list, which is 1000, cannot be altered during
program execution.
The value of list is constant. Therefore, the increment and decrement
operations cannot be applied to list.
Functions and Pointers :
A pointer variable can be passed as a parameter to a function either by

value or by reference.

Pass By Value:
To declare a pointer as a value parameter in a function heading, you
use the same mechanism as you use to declare a variable.
Pass By Reference:
• To make a formal parameter be a reference parameter, you use & when
you declare the formal parameter in the function heading.

• Therefore, to declare a formal parameter as a reference pointer


parameter, between the data type name and the identifier name, you
must include * to make the identifier a pointer and & to make it a
reference parameter.
• In C++, to make a pointer a reference parameter in a function
heading, * appears before the & between the data type name and
the identifier.

void pointerParameters(int* &p, double *q)


{
.
.
.
}
• The parameter p is a reference parameter; the parameter q is a value
parameter.
• Furthermore, the function pointerParameters can change the value of
*q, but not the value of q.
• However, the function pointerParameters can change the value of
both p and *p.
Pointers and Function Return Values :
In C++, the return type of a function can be a pointer. For example, the
return type of the function
int* testExp(...)
{
.
.
.
}
is a pointer of type int.
The this Pointer :
• The this pointer is a special built-in pointer that is available to a class’s
member functions. It always points to the instance of the class making the
function call.

• Friend functions do not have a this pointer, because friends are not
members of a class. Only member functions have a this pointer.
class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2

if(Box1.compare(Box2)) {
cout << "Box2 is smaller than Box1" <<endl;
} else {
cout << "Box2 is equal to or larger than Box1" <<endl;
}

return 0;
}

You might also like