Data Structure Lecture 5
Data Structure Lecture 5
Algorithms
Chapter 3
Lecture 3
• Pointer variable: A variable whose content is an
address (that is, a memory address).
• dataType *identifier;
Example
int *p;
char *ch;
int* p, q;
In this statement, only p is a pointer variable, not
q.
The Pointer int *p, *q;
declares both p and q to be pointer variables of
type int.
In C++, the ampersand, &, called the address of
operator
int x;
int *p;
p = &x;
assigns the address of x to p. That is, x and the
value of p refer to the same memory location.
Example 1
int *p;
int num;
num = 78;
p = #
*p = 24;
Pointers and Classes
string *str;
str = new string;
*str = "Sunny Day";
The syntax for accessing a class (struct) member using the operator -> is as follows:
pointerVariableName->classMemberName
(*str).length()
is equivalent to the expression
str->length()
delete p;
delete str;
One way to avoid this pitfall is to set these pointers to NULL after
the delete operation.
Operations on Pointer Variables
int *p, *q;
The statement
p = q;
copies the value of q into p. After this statement executes, both p and q
point to the same memory location.
Any changes made to *p automatically change the value of *q, and vice
versa.
Operations on Pointer Variables
Dynamic Arrays
An array created during the execution of a program is called
a dynamic array.
To create a dynamic array
int *p;
p = new int[10];
allocates 10 contiguous memory locations, each of type int, and stores
the address of the first memory location into p.
*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.
After performing a few increment operations, it is possible to lose
track of the first array component.
C++ allows us to use array notation to access these memory
locations.
Dynamic Arrays
Dynamic Array