Introduction To Programming: Engr. Rashid Farid Chishti
Introduction To Programming: Engr. Rashid Farid Chishti
Introduction To Programming: Engr. Rashid Farid Chishti
Pointers
Pointer Variable
// ptrvar.cpp
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int var1 = 11; // two integer variables
int var2 = 22;
cout << &var1 << endl //print addresses of variables
<< &var2 << endl << endl;
int* ptr;
// pointer to integers
ptr = &var1;
// pointer points to var1
cout << ptr << endl; // print pointer value
ptr = &var2;
// pointer points to var2
cout << ptr << endl; // print pointer value
system("PAUSE"); return 0; }
Pointer Variable
// accessing the variable pointed to
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int var1 = 11;
// two integer variables
int var2 = 22;
int* ptr;
// pointer to integers
ptr = &var1;
// pointer points to var1
cout << *ptr << endl; // print contents of pointer (11)
ptr = &var2;
// pointer points to var2
cout << *ptr << endl; // print contents of pointer (22)
system("PAUSE");
return 0;
}
Pointer Variable
// other access using pointers
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int var1, var2;
// two integer variables
int* ptr;
// pointer to integers
ptr = &var1;
// set pointer to address of var1
*ptr = 37;
// same as var1 = 37
var2 = *ptr;
// same as var2 = var1
cout << var1 << endl; // verify var2 is 37
cout << var2 << endl; // verify var2 is 37
system("PAUSE");
return 0;
}
Pointer to void
// pointers to type void
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int intvar;
// integer variable
float flovar;
// float variable
int* ptrint;
// define pointer to int
float* ptrflo;
// define pointer to float
void* ptrvoid;
// define pointer to void
ptrint = &intvar; // ok, int* to int*
// ptrint = &flovar;
// error, float* to int*
// ptrflo = &intvar;
// error, int* to float*
ptrflo = &flovar;
// ok, float* to float*
ptrvoid = &intvar;
// ok, int* to void*
ptrvoid = &flovar;
// ok, float* to void*
system("PAUSE"); return 0; }
Pointer Arithmatic
// Adding and Subtracting a pointer variable
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int intarray[] = { 31, 54, 77, 52, 93 }; //array
int* ptrint;
// pointer to int
ptrint = intarray;
// points to intarray
cout << *ptrint << endl;
// print at index 0;
ptrint = ptrint + 2;
cout << *ptrint << endl;
// print at index 3;
ptrint++; cout << *ptrint << endl;
// print at index 4;
ptrint = ptrint-2;
cout << *ptrint << endl;
// print at index 1;
ptrint--; cout << *ptrint << endl;
// print at index 0;
system("PAUSE"); return 0;
}