Chapter02 - Pointers
Chapter02 - Pointers
Chapter 2:Pointer
Miss:Hanan Hardam
1
++Pointers in C
Topics to cover:
• Overview of Pointers
• Pointer Declaration
• Pointer Assignment
• Pointer Arithmetic
2
Overview of Pointers
3
Pointer Declaration
4
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
5
Cont. Example
1. int *xPtr, *yPtr; int x = 5;
2. xPtr = & x;
3. yPtr = xPtr;
6
Cont. Example
4. cout << *xPtr;
// this statement should print the value that is pointed
to by xPtr, which is 5.
5. cout<< xPtr;
// this statement should print the contents of xPtr
location, which is the address 1008.
8
Examples on Pointers
//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;
}
9
Call by Reference
#include <iostream.h>
void Increment(int&);
void main() {
int A = 10;
Increment(A);
cout<<A<<endl;
}
void main() {
int A = 10;
Increment(&A);
cout<<A<<endl;
}
#include <iostream.h>
void Increment(int*);
void main() {
int A = 10;
cout << "in main "<< &A<< endl;
Increment(&A);
cout<<A<<endl;
}
void Increment(int *X)
{ ++*X;
cout << "in fun X "<< X << endl;
cout << "in fun *X "<< *X << endl;
cout << "in fun &X"<< &X <<endl;
}
13
Examples on Pointers (Cont.)
//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; // here the values which a and b point to are swapped
*a = *b;
*b = temp;
}
14