Pointers Part 1
Pointers Part 1
Pointers
Pointer
It is special type of variable that holds the address of a conventional (simple) variable as a
value
• Basic Syntax:
< data - type > * < identifier > = & < identifier >;
int main () {
int x = 5;
int * p = & x ;
cout < < " value of x : " <<x < < endl ;
cout < < " Address of x : " < <&x < < endl ;
cout < < " value of p : " <<p < < endl ;
cout < < " Address of p : " < <&p < < endl ;
cout < < " value of * p : " < <*p < < endl ;
}
int main () {
int x = 5;
int * p = & x ;
cout < < " value of x : " <<x < < endl ;
cout < < " Address of x : " < <&x < < endl ;
cout < < " value of p : " <<p < < endl ;
cout < < " Address of p : " < <&p < < endl ;
cout < < " value of * p : " < <*p < < endl ;
}
int main () {
int x = 5;
int * p = & x ;
cout < < " value of x : " <<x < < endl ;
cout < < " Address of x : " < <&x < < endl ;
cout < < " value of p : " <<p < < endl ;
cout < < " Address of p : " < <&p < < endl ;
cout < < " value of * p : " < <*p < < endl ;
}
int main () {
char c = ’a ’;
char * p = & c ;
cout < < " value of c : " <<c < < endl ;
cout < < " Size of c : " << sizeof ( c ) << endl ;
cout < < " value of * p : " < <*p < < endl ;
cout < < " Size of p : " << sizeof ( p ) << endl ;
}
int main () {
char c = ’a ’;
char * p = & c ;
cout < < " value of c : " <<c < < endl ;
cout < < " Size of c : " << sizeof ( c ) << endl ;
cout < < " value of * p : " < <*p < < endl ;
cout < < " Size of p : " << sizeof ( p ) << endl ;
}
int main () {
int * x = new int ;
*x = 1 ;
cout < < " \ n & x = " < <&x < < endl ;
cout < < " x = " <<x < < endl ;
cout < < " * x = " < <*x < < endl ;
}
int main () {
int * array = new int [3];
array [0] = 2;
array [1] = 5;
array [3] = 7;
cout < < " & array = " < <& array < < endl ;
cout < < " array = " << array < < endl ;
cout < < " & array [0] = " < <& array [0] < < endl ;
cout < < " array [0] = " << array [0] < < endl ;
cout < < " & array [1] = " < <& array [1] < < endl ;
cout < < " array [1] = " << array [1] < < endl ;
cout < < " & array [2] = " < <& array [2] < < endl ;
cout < < " array [2] = " << array [2] < < endl ;
}
Usman Wajid Object Oriented Programming Pointers 9 / 10
The new Keyword Example 3
int main () {
int * array = new int ;
* array = 2;
cout < < " array = " << array < < endl ;
cout < < " * array = " < <* array < < endl ;
array ++;
* array = 5;
cout < < " array = " << array < < endl ;
cout < < " * array = " < <* array < < endl ;
array ++;
* array = 7;
cout < < " array = " << array < < endl ;
cout < < " * array = " < <* array < < endl ;