Pointers in C++ Programming
Pointers in C++ Programming
BSE 1
Joddat Fatima
1
[email protected]
Department of C&SE
Bahria University Islamabad
REFERENCE OPERATOR (&)
This would assign to ted the address of variable andy, since when
preceding the name of the variable andy with the reference
operator (&) we are no longer talking about the content of the
variable itself, but about its reference (i.e., its address in
memory).
4
DEREFERENCE OPERATOR (*)
We have just seen that a variable which stores a reference to
another variable is called a pointer.
6
& AND * DIFFERENCE
7
POINTERS
8
INTRODUCTION
We have already seen how variables are seen as memory cells that
can be accessed using their identifiers.
This way we did not have to care about the physical location of our
data within memory, we simply used its identifier
is a pointer
Pointers "point" to a variable by telling where the variable is
located
Example:
v1 = 0; p1 = &v1; *p1 = 42; output:
cout << v1 << endl; 42
cout << *p1 << endl; 42
13
EXAMPLE
#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0; 14
}
EXAMPLE EXPLANATION
#include <iostream>
using namespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed by p1 = 10
*p2 = *p1; // value pointed by p2 = value pointed by p1
p1 = p2;// p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0; 16
}
POINTERS AND ARRAYS
Well, these bracket sign operators [] are also a dereference operator known as
offset operator.
They dereference the variable they follow just as * does, but they also add the
number between brackets to the address being dereferenced.
For example:
a[5] = 0; // a [offset of 5] = 0
*(a+5) = 0; // pointed by (a+5) = 0