Wednesday, April 25, 2012

What is pointer

A pointer stores an address, so when you use the bare pointer, you get that address back. you have to add something extra, the asterisk(*), in order to retrieve or modify the value stored at the address.

A variable stores a value, so when you use the variable, you get its value. you have to add some extra, the ampersand(&), in order to retrieve of that variable.
  • Pointer contain an address, not data.
  • Normal variable -- storage location.
  • Pointer -- A variable that holds an address as its value.  
// simple pointer program
#include <iostream>
using namespace std;

int main()
{
    int x;        //A normal integer
    int *p_int;   // A pointer to an integer  (declaration of pointer)
   
    p_int = &x;    //Read it, "assign the address of x to p_int" (definition of pointer)
    cout << "Please enter a number: ";
    cin >> x;
   
    cout << *p_int << '\n';   //Note the use of the * to get the value
    *p_int = 10;
   
    cout << x;   // output 10 again!   
}

OUTPUT:
Please enter a number: 12
12
10

Note: pointer is a datatype.
  • Size of pointer datatype is dependent according to OS architecture.
  • In 32-bit system size of pointer datatype is 4 byte and in 64-bit it is 8 byte.
  • Byte is a datatype (size is 8 bit) (what is datatype of byte? ; byte to khud datatype hai)
Pointers are of pointer type. If you're asking about how pointer values are represented in memory, that really depends on the platform. They may be simple integral values (as in a flat memory model), or they may be structured values like a page number and an offset (for a segmented model), or they  may be something else entirely. 
-----------------------------------------------------------------------------------------------
// Interview Question
#include <iostream>
using namespace std;

int main()
{
    int x=5;
    int * p;
   
    *p = 8;
    cout << *p << endl;
   
    *p = x;   
   
    cout << *p << endl;
   
    *p = 6;
    cout << *p << endl;
   
    cout << x;
}

OUTPUT:
8
5
6
5


*p = x;  yeh pointer hi nahi bna,
*p = 6;  to x ki value 6 koi ho jayegi 

-----------------------------------------------------------------------------------------------
//For more light on pointer concept
#include <iostream>
using namespace std;

int main()
{
    int i=3;
    int *j;
   
    j = &i;
    cout << "\n Address of i (&i): " << &i << endl;
    cout << "\n  Address of i (j): "  << j << endl;
    cout << "\n Address of j (&j): "  << &j << endl;
    cout << "\n    value of j (j): "  << j << endl;
    cout << "\n    value of i (i): "  << i << endl;
    cout << "\nvalue of i [*(&i)]: "  << *(&i) << endl;
    cout << "\n   value of i (*j): "  << *j << endl;
    return 0;
}


OUTOUT: 

More on pointer

BY: Dheeraj Singh (Galgotia college) 

 

No comments:

Post a Comment