7.Cpp Arrays

Previous 6.cpp <<


 Arrays 


General Syntax : 
    reading 
    /for loop 
    for( int i =0 ; i < n ; i++ ) { 
        cout << arr [i] << ",";
    }

    for ( int x : arr ) { // called for each loop 
        cout << x << ",";
    }

Passing of array to a function 
    
    void print(int a[], int n) {
        for (int i =0 ; i<n ; i++ ) {
            cout << a[i] << " ,";
        }
    } 

    int main ( ) {
        int arr[n]; 
        ...
        ...
        print( arr ,n ) ;  / / arr is pointer 

note :: pointer can be reassigned to some other value but pointer can not be reassigned .


Static Vs Dynamic Array :

way i : static allocation : 
 in stack memory 
stack memory destroys after use , so we can't initilize array in stack memory which are suppose to be later used in main memory 
    
example 
    int n ;
    cin>> n;
    int a[n];
    for(int i=0; i<n;i++){
        cin>>a[i];
    }
    for(int x: a){
        cout<<x<<endl;
    }


way ii : dynamic allocation : 
    occurs in heap memory , heap is that part which don't destroyed after function call ends 
    actually don't get destroyed automatically by itself when function call ends in heap 
    we have to manually destroy or release the memory later on 
    
syntax 
    int *a = new int[n] ; 
    ....
    delete [] a ; 

         


Comments

Popular posts from this blog