Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance variable value not printing properly

Tags:

c++

oop

I am using a constructor to initialize the instance variable. When I print the instance variable it gives wrong output.

int main(){
    int k[]={1,2,4};  
    int hs=3;  
    int n=3;  
    priorityq p(k,hs,n);  
    p.printKey();  
}  
class priorityq{  
    int key[];  
    int heapsize;  
    int n;  
public:  
    void printKey();  
    priorityq(int k[],int hs, int ni);  
};  
priorityq::priorityq(int k[],int hs, int ni){  
     for(int i=0;i<ni;i++)  
      key[i]=k[i];  
     heapsize=hs;   
     n=n_i;   
}
void priorityq::printKey(){     
     for(int i=0;i<heap_size;i++)   
       cout<<key[i]<<" ";   
     cout<<endl;    
}

I expect output to be 1 2 4 but am getting 3 3 4

like image 666
Eragon Avatar asked Jun 12 '26 15:06

Eragon


1 Answers

Use std::array if you are using c++, or better for dynamic-ranged arrays, use std::vector. And instead of using []-operator use the at() method, which checks for out-of-bound errors:

Edit, there was an error in the constructor

int main(){
    std::vector<int> k{1,2,4};  
    int hs=3;  
    int n=3;  
    priorityq p(k,hs,n);  
    p.printKey();  
}  

..

class priorityq{  
    std::vector<int> key;  
    int heapsize;  
    int n;  
public:  
    void printKey();  
    priorityq(std::vector<int>& k,int hs, int ni);  
};  

..

priorityq::priorityq(std::vector<int>& k,int hs, int ni){  
     for(int i=0;i<ni;i++)  
      key.push_back(k.at(i));  
     heapsize=hs;   
     n=n_i;   
}
void priorityq::printKey(){     
     for(int i=0;i<heap_size;i++)   
       cout<<key.at(i)<<" ";   
     cout<<endl;    
}
like image 74
RoQuOTriX Avatar answered Jun 15 '26 07:06

RoQuOTriX