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

C++ Session 2

programmation with c++

Uploaded by

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

C++ Session 2

programmation with c++

Uploaded by

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

Pointers and References

• Session 7
• By
[email protected]
Pointer Variable (Pointer)
• A pointer variable (or pointer in short) is
basically the same as the other variables,
which can store a piece of data.
• Unlike normal variable which stores a value
(such as int, double, char etc), a pointer
stores a memory address.
Pointers
• Using them correctly could improve
efficiency and performance
• Using them incorrectly could lead to many
problems of unreadable and unmaintainable
codes, bug, memory leaks and buffer overflow
which may expose your system to hacking.
• Many new languages such as java and c#
have removed them from their syntax.
Pointers Cont.
• A pointer is associated with a type (such as int
and double etc).
• Pointers must be declared before they can be
used, just like a normal variable.
• The syntax of declaring a pointer is to place
an * in front of the name.
Declaration
• type *ptr; // Declare a pointer variable called ptr
as a pointer of type or
• type* ptr; // or
• type * ptr; // I shall adopt this convention
Example
• int * iPtr; // Declare a pointer variable //called
iPtr pointing to an int (an int pointer)
• // It contains an address. That address holds an
int value.
• double * dPtr; // Declare a double pointer
Note
• Take note that you need to place an * in front
of each pointer variable, in other words *
applies only to the name that followed.
• The * in the declaration statement is not an
operator, but indicates that the name
followed is a pointer variable.
• Examples on next slide,
Example
int *p1,*p2, i;// p1 and p2 are int pointers, i is
an int
int* p1, p2, i; // p1 is a int pointer, p2 and i
are int
float * p1,*p2,i; // p1 and p2 are float pointers,
i is a float
string * Amanda, yam, *okro,babe;
//Amanda and okro are string pointers while
yam and babe are strings
Initialization of pointer via address of
operator (&)
• When you declare a pointer variable, its
content is not initialized.
• In other words, it contains an address of
"somewhere", which is of course not a valid
location.
• This is dangerous! You need to initialize a
pointer by assigning it a valid address.
• This is normally done via the address-of
operator (&).
Uninitialized pointer are serious
logical error
int * iPtr;
*iPtr = 55; //Error
cout << *iPtr << endl;
The pointer iPtr was declared without initialization, It
is pointing to "somewhere" which is of course an
invalid memory location.
The *iPtr = 55 corrupts the value of "somewhere"! You
need to initialize a pointer by assigning it a valid
address.
Some compilers do not signal an error or a warning for
uninitialized pointer?!
Initialization
• The address-of operator (&) operates on a
variable, and returns the address of the variable.
• For example, if number is an int variable,
&number returns the address of the
variable number.
Pointer Initialization
• int number = 88; // An int variable with value 88
• int * pNumber; // Declare a pointer variable
called pNumber pointing to an int (or int pointer)

• pNumber = &number; // Assign the address of


the variable number to pointer pNumber

• int * pAnother = &number; // Declare another int


pointer and initializes it to address of the variable
number
0x69fee8
#include <iostream> 88
using namespace std; 99
int main() { 99
int number = 88; 0x69fee8
int * pNumber = &number; // Declare and assign the
address of variable number to pointer pNumber
cout << pNumber<< endl //print the address pointed to
cout << *pNumber << endl; // Print the value "pointed
to" by the pointer, which is an int (88)
*pNumber = 99; // Assign a value to where the pointer
is pointed to, NOT to the pointer variable
cout << *pNumber << endl; // Print the new value
"pointed to" by the pointer (99)
cout << number << endl; // Print the number (99)
cout << pNumber << endl; // Print the address of (99) }
Caution (you can’t swap variable
types referencing)
A pointer is associated with a type (of the value
it points to), which is specified during
declaration.
A pointer can only hold an address of the
declared type; it cannot hold an address of a
different type.
You cannot swap an integer pointer for float, or
double for float etc.
Type Swapping (incorrect)
int i = 88; // int variable
double d = 55.66; // double variable
int * iPtr = &i; // int pointer pointing to an int value
double * dPtr = &d; // double pointer pointing to a double value

iPtr = &d; // ERROR, cannot hold address of different type


dPtr = &i; // ERROR
iPtr = i; // ERROR, pointer holds address of an int, NOT int value

int j = 99;
iPtr = &j; // You can change the address stored in a pointer
// initially pointing to i but now pointing to j
#include <iostream>
using namespace std;

int main() {
0x69feec
int num = 88;
0x69feec
int * pNum;
88
pNum = &num;
88
cout << pNum << endl;
0x69feec
cout << &num << endl;
0x69feec
cout << *pNum << endl;
99
cout << num << endl;
99
*pNum = 99;
0x69fee8
cout << pNum << endl;
cout << &num << endl;
cout << *pNum << endl;
cout << num << endl;
cout << &pNum << endl; }
#include <iostream>
using namespace std;
int main()
{
output
int r = 16, *k, y=14,*s; 0x69fee4
k = &r; 0x69fee0
s= & y; 0x69fee0
cout << k << endl; 14
cout<<s<<endl;
k=s;
cout<<k<<endl;
cout<<*k;
return 0; }
#include <iostream>
using namespace std;
int main()
{
int r = 16, *k, y=14,*s;
k = &r; Output
s= & y; 0x69fee4
cout << k << endl; 0x69fee0
cout<<s<<endl; 30
*k=*s+r;
cout<<*k;
return 0;
}
#include <iostream>
using namespace std;
int main()
{ int r = 16, *k, y=14,*s;
k = &r; Output
s= & y; 0x69fee4
cout << k << endl; 0x69fee0
cout<<s<<endl; 62
*k=*s+r+2*(*k);
cout<<*k;
return 0;
}
Null Pointer
• You can initialize a pointer to 0 or NULL, i.e. it
points to nothing.
• This is called a null pointer.
#include <iostream>
using namespace std;
address of p is 0
int main() address of q is 0
{
int *p =0; //declare int pointer and initialize the
pointer to point at nothing
double *q = NULL; //declare NULL pointer pointing to
nothing
cout<< *p<<endl; //Error or nothing is displayed
cout<<"address of p is "<<p<<endl;
cout<<"address of q is "<<q<<endl;
return 0;
}
#include <iostream> 0x61fe0c is the address of k
using namespace std; 0x61fe08 is the address of t
int main() value of k is 5
{ k1 is now pointing to 0x61fe08
int *k1, *t1, k = 5, t=7; value of k is 7
k1 =& k;
t1 = &t;
cout<<k1<<" is the address of k\n";
cout<<t1<<" is the address of t\n";
k1=t1; //k1 address changed to t1
cout<<"k1 is now pointing to "<<k1<<endl;

return 0;
}
#include <iostream>
using namespace std;
int main()
{ The address of p is 0x69fee8
int p = 7, * y; Y is now pointing to 0x69fee8
y =& p;
cout<<"The address of p is " <<y<<endl;
cout<<"y is now pointing to "<<y++;
//same address
return 0; }
Dynamic Memory Allocation
#include <iostream>
using namespace std; Dynamic Pointer Value: 123
int main() {
int* dynamicPtr = new int;// dynamic int memory allocation
*dynamicPtr = 123; //initialize pointer
cout << "Dynamic Pointer Value: " << *dynamicPtr << endl;
delete dynamicPtr; // Release allocated memory
return 0;
}
• #include <iostream>
• using namespace std;
• int main() {
• // Dynamic allocation of an integer
• int* dynam = new int;
• // Assign value What is the output
• *dynam = 42;
• // Use the dynamically allocated variable
• cout << "Dynamic Integer Value: " << *dynam<< endl;
• // Deallocate memory
• delete dynam;
• return 0;
• }
#include <iostream>
using namespace std;
int main()
{ int *p1,*p2;
p1 = new int; //dynamic allocation *p1 = 42
*p1 = 42; *p2 = 42
p2=p1; //p2 now pointing to p1
cout<<"*p1 = "<<*p1<<endl; *p1 = 53
cout<<"*p2 = "<<*p2<<endl; *p2 = 53
*p2 = 53; *p1 = 88
cout<<"*p1 = "<<*p1<<endl;
*p2 = 53
cout<<"*p2 = "<<*p2<<endl;
p1 = new int; //dynamic allocation
*p1 = 88; //only p1 has changed
cout<<"*p1 = "<<*p1<<endl;
cout<<"*p2 = "<<*p2<<endl;
Delete i1, p2; //release dynamic memory
}
Arrays and Pointers:
#include <iostream>
using namespace std;
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int* ptr = numbers;
for (int i = 0; i < 5; ++i) {
cout << "Element " << i << ": " << *ptr << endl;
++ptr;
}

return 0;
}
#include <iostream>
using namespace std;
int main() {
int vals[] = {4, 7, 11}; 4
cout << vals[0]<<endl; // displays 4
//Lets take an example: 0x61fe0c
int *ptr = vals; 0x61fe10
cout<<ptr<<endl; //address of array [4] 7
ptr++; //point to address of 7
cout<<ptr<<endl; //address of 7
0x61fe14
cout<<*ptr<<endl; //value of 7 11
ptr++; //pointing to 11 0x61fe18
cout<<ptr<<endl; //address of 11 6422040
cout<<*ptr<<endl; //value of 11
ptr++; //out of the array
cout<<ptr<<endl;
cout<<*ptr<<endl; //semantic error }
Pointer to Pointer:
• #include <iostream> Value: 42
• using namespace std; Value of single pointer: 42
• int main() { Value of double pointer: 42
• int value = 42; address of ptr is 0x61fe10
• int* ptr = &value; address of ptrToPtr is 0x61fe08
• int** ptrToPtr = &ptr;

• cout << "Value: " << value << endl;


• cout << "Value through single pointer: " << *ptr << endl;
• cout << "Value through double pointer: " << **ptrToPtr << endl;
• cout<<"address of ptr is "<<ptrToPtr<<endl;
• cout<<"address of ptrToPtr is "<<&ptrToPtr<<endl;
• return 0;
• }
Pointers and Constants
• #include <iostream> Value through const pointer: 10
• using namespace std; You cannot reassign
• int main() {
• const int constValue = 10;
• const int* constPtr = &constValue;
• cout << "Value through const pointer: " <<
*constPtr;
• return 0;
• }
Pointers and Constants
#include <iostream>
using namespace std; Can be modified
int main() {
// Variable
Cannot be reassigned
int number = 99;
int y = 11;
// Constant pointer to a variable e.g. constPtr = & y;
int* const constPtr = &number;
cout << "Value through constant pointer: " << *constPtr <<endl;
// Modify the value through the constant pointer
*constPtr = 123;
cout << "Modified value through constant pointer: " <<
*constPtr << endl;
return 0;
}
Reference
• A reference is an alias or alternate name to an
existing variable.
• Supposing your name is Barbara, if your
friends decide to call you Barbs. Then Barbs is
an alias to Barbara
• There cannot be Barbs without Barbara.
• You have to initialize a reference when
created.
Reference Syntax

• We use & as an operator for referencing


• type &newName = existingName; or
• type& newName = existingName; or
• type & newName = existingName; // I shall
adopt this convention
Example
• int num = 88; // Declare an int variable
called num
• int & refNum = num; // Declare a
reference (alias) to the variable num
• double domi = 15.87; // Declare a double
variable called domi
• double & refdomi = domi; // Declare a
reference (alias) to the variable refdomi
Reference Cont.
#include <iostream>
using namespace std; Result
int main () Value of k is 17
{// declare and initialize a variable
Address of k is 0x69fee0
float k = 17; Reference value of k is 17
//declare a reference & initialize it
float & l = k;
cout<<"Value of k is "<<k<<endl;
cout<<“Address of k is "<<&l<<endl;
cout<<"Reference of k is "<<l<<endl<<endl;
return 0;
END

You might also like