6. Pointer and Adress


Address of Operator 
    
    // except character and string 
    // other datatype 's address can be directly accessed by &
    
    for example 
    int main() {
        int x =10 ;
        cout << (&x) << endl; // memory address of x
        cout << (&x) +1 << endl; // memory address of x + 4 bits ahead 
        
        float z = 5.5 ; 
        cout << &z << endl ; 
            
        char y = 'A';
        cout<< &y << endl;  // output : A
        cout<< (void *)&y <<endl; // output : address of y
        ....
    }


Pointers 
    // generally have storage of hexadecimal type with 11 bits  10 bits of storage and one for sign 
    are the datatype used to store addresses of variables and data
    example 
        ...
        int x =5;           // stores 5 in x 
        int* Xptr = &x; // storing address of x in Xptr 
        cout << "Xptr : " << Xptr << endl;
        cout << "X  :    " << x <<endl :
        cout << "address of x " << &x 

        float z = 5.5 ;
        float* Zptr = &z;
        cout<< "Zptr :: " << Zptr <<endl;
        cout<< "address of z" << &z <<endl;
        
        .... 
        
De-Reference Operator 
    for getting value stored in the pointer's address memory 
     // * operator 
     //There are three uses of datatype 
     // first is multiplication, the second is the declaration of a pointer variable, the third one is dereferencing 
     
... 
int x = 5; 
int* Xptr = &x ;
cout << " x is : " << x<<endl;
cout << " x is : " << *Xptr << endl;
cout << " address of x : " << &x <<endl;
cout << " address of x : " << Xptr << endl;
    
    

Call By Value and Call By Reference 
    calling a function just by value is called call by value 
        in call by value the value of a variable is copied to another variable passed to function 
    calling a function by reference is called call by reference 
        in call by reference the variable's address is passed hence no new variable is created instead that original variable is manipulated 

example 
    call by value 
    void doubleMoney( int money ) { cout<< " your money inside function " << money*2 << endl; }
int main () { doubleMoney( money ) ;


    call by reference/ actually address 
    void doubleMoneyR( int*m) { (*m) = 2*(*m); cout << " your money inside function "<< *m << endl ; }
int main () { doubleMoneyR( &money );


Reference variable 

int main() {
    int x =10 ;
    int &y = x ; // y act as alias to x , // y must be initialized with some variable or value 
    // update of y will also update x 
}

Call by Reference better version 
void doubleMoney ( int &money ) { money = money*2 ;  cout << " your money inside function " << money << endl ; }  
int main () {
    doubleMoney( money );



    

    

Comments

Popular posts from this blog