Programming with Passion

Make the best out of everything.

Saturday, 26 March 2016

C++ Pointers

Example 2: C++ Pointers

C++ Program to demonstrate the working of pointer.
#include <iostream>
using namespace std;
int main() {
    int *pc, c;
    
    c = 5;
    cout<< "Address of c (&c): " << &c << endl;
    cout<< "Value of c (c): " << c << endl << endl;

    pc = &c;    // Pointer pc holds the memory address of variable c
    cout<< "Address that pointer pc holds (pc): "<< pc << endl;
    cout<< "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;
    
    c = 11;    // The content inside memory address &c is changed from 5 to 11.
    cout << "Address pointer pc holds (pc): " << pc << endl;
    cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

    *pc = 2; 
    cout<< "Address of c (&c): "<< &c <<endl;
    cout<<"Value of c (c): "<< c<<endl<< endl;

    return 0;
}
Output
Address of c (&c): 0x7fff5fbff80c
Value of c (c): 5

Address that pointer pc holds (pc): 0x7fff5fbff80c
Content of the address pointer pc holds (*pc): 5

Address pointer pc holds (pc): 0x7fff5fbff80c
Content of the address pointer pc holds (*pc): 11

Address of c (&c): 0x7fff5fbff80c
Value of c (c): 2
Working of pointer in C++ programming
Explanation of program
  • When c = 5; the value 5 is stored in the address of variable c.
  • When pc = &c; the pointer pc holds the address of c and the expression *pccontains the value of that address which is 5 in this case.
  • When c = 11; the address that pointer pc holds is unchanged. But the expression*pc is changed because now the address &c (which is same as pc) contains 11.
  • When *pc = 2; the content in the address pc(which is equal to &c) is changed from 11 to 2. Since the pointer pc and variable c has address, value of c is changed to 2.

No comments:

Post a Comment