Pointer C++
Pointer C++
1
++Pointers in C
Topics to cover:
• Overview of Pointers
• Pointer Declaration
• Pointer Assignment
• Pointer Arithmetic
• Relations Between Pointers and Arrays
• Pointers and Strings
2
Reference and Pointer
Variables
The object hello occupies
some computer memory.
.Variable and object values are stored in particular locations in the computer’s memory •
.Reference and pointer variables store the memory location of other variables •
Pointers are found in C. References are a C++ variation that makes pointers easier and safer to •
.use
.More on this topic later in the tutorial •
Overview of Pointers
4
Pointer Declaration
5
Pointer Assignment
• Assignment can be applied on pointers of the same type
• If not the same type, a cast operator must be used
• Exception: pointer to void does not need casting to convert a
pointer to void type
• void pointers cannot be dereferenced
• Example
int *xPtr, *yPtr; int x = 5;
…
xPtr = & x; // xPtr now points to address of x
yPtr = xPtr; // now yPtr and xPtr point to x
6
Pointer Arithmetic
7
Pointer Arithmetic (Cont.)
• Example
Consider an integer array of 5 elements on a machine using 4
bytes for integers.
1000 1004 1008 1012 1016
8
Pointer Arithmetic (Cont.)
• Subtracting pointers
- Returns the number of elements between two
addresses
9
Relations Between Pointers and Arrays
10
Relations Between Pointers and Arrays (Cont.)
11
Examples on Pointers
//File: swap.cpp
//A program to call a function to swap two numbers using reference parameters
#include <iostream.h>
void swap(int *, int *); // This is swap's prototype
void main()
{ int x = 5, y = 7;
swap(&x , &y); // calling swap with reference parameters
cout << "\n x is now "<< x << " and y is now " << y << '\n';
}
// swap function is defined here using dereferencing operator ‘*’
void swap(int *a, int *b)
{ int temp;
temp = *a;
*a = *b;
*b = temp;
}
12
Examples on Pointers (Cont.)
//File: pointers.cpp
//A program to test pointers and references
#include <iostream.h>
void main ( )
{ int intVar = 10;
int *intPtr; // intPtr is a pointer
intPtr = & intVar;
cout << "\nLocation of intVar: " << & intVar;
cout << "\nContents of intVar: " << intVar;
cout << "\nLocation of intPtr: " << & intPtr;
cout << "\nContents of intPtr: " << intPtr;
cout << "\nThe value that intPtr points to: " << * intPtr;
}
13
When calling, the pointer formal parameter will points to the
.actual parameter
#include <iostream.h>
void Increment(int*);
void main() {
int A = 10;
Increment(&A);
cout<<A<<endl;
}