开发者

array class nodes not work

i have following code,which does not show me anything

#include <iostream>
using namespace std;
class Array{

private :
     long *a;
public:
       Array(int size){
        a=new  long[size];


       }
       void set(int index,long  value){
        a[index]=value;

       }
       long get(int index){
        if (index<0 || index>(sizeof(a)/sizeof(long)))    {

         exit(1);
        }
         return a[index];
       }







} ;
int main(){

      Array* arr=new Array(100);
             int number=0;
             int j=0;
             arr->set(0,11);
             arr->set(1,12);
             arr->set(2,14);
             arr->set(3,15);
             arr->set(4,20);
             arr->set(5,34);
             arr->set(6,50);
             arr->set(7,10);
             arr->set(8,80);
             arr->set(9,100);
             number=10;
             int search=80;
              for (int i=0;i<number;i++){
                  if (arr->get(i)==search){
                   cout<<"search found "<<endl;
                   break;
                  }



                  }


                    //cout<<arr->get(8)<<endl;  

 return 0;
}

there is not any error or bugs,just no output,what is wrong?please help me UPDATED: why following code

int k=10;//delete it;
                     for (int j=0;j<number;j++)
                         if (arr->get(j)==k)
                              break;
                          for (k=j;k<number-1;k++)
                              arr->set(k,arr->get(k+1));
         开发者_运维百科           number--;

                     for (int j=0;j<number;j++)
                         cout<<arr->get(j)<<"  ";

deletes 11 and not 10?old problem is fixed introduce new variable for counting size of array,but this problem i have now


The problem is that you assume that sizeof(a) gives you the size of memory a points to. It doesn't. It gives you size of a pointer. You have the size argument in the constructor - just save it in a member variable and use later for bounds checking.


index>(sizeof(a)/sizeof(long))

Is wrong. You're taking the size of a pointer, not the size of your array...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜