在构造函数中传递数组的C ++程序中,执行停止 [英] In C++ program which passes array in constructor, execution stops

查看:150
本文介绍了在构造函数中传递数组的C ++程序中,执行停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果数组包含这些索引作为其元素,我试图将索引处的集合的元素设置为1。数组大小为20即索引0到19

I am trying to set elements of a set at an index to 1 if an array contains those indices as its elements. Array size is 20 i.e. index 0 to 19

对于ex -

 int myArray[5] = {1,4,2}; //user input or statically defined in driver(main)
 int set[] = {0,1,1,0,1}; //successfully set in constructor
 IntegerSet intObj(set);//At a point, program stops execution. Any idea why?

以下是部分代码

    //integerset.h 

    class IntegerSet{
          public :
              IntegerSet( int [] );
              .....
          private :
              int set[20];            
    };

  //integerset.cpp (header files included)

  IntegerSet :: IntegerSet( int arr[]){
       for(int i = 0; i <20; i++) //works fine (printed "test" in loop)
               set[i] = 0; //if not this then garbage elems set
       for ( int i = 0; arr[i] != '\0' ; i++ ) //works fine. (printed "test" in loop)
          set [arr[i]] = 1;        
       for ( int i = 0; i < 20; i++ ) //program stops execution here
           cout<<i<<"\t"<<set[i]<<"\n"; //tried to print "test" in loop,program crashed
  }

  //main.cpp (header files included)


int main(){
             int a[] = {1,3,0,12,14,15,'\0'}; // premature end??
             IntegerSet obj2(a);
             system("pause");
             return 0;
   }


推荐答案

> arr [i]!='\0',你的数组没有一个null终止符,所以循环继续并且索引元素通过数组的末尾。

In arr[i] != '\0', your array does not have a null terminator, so the loop continues and indexes elements pass the end of the array.

最好使用 std :: array std :: vector 。另一个选项是以下修正您的代码:

It is best practice to use std::array or std::vector. Another option is the following fix to your code:

template <int N>
IntegerSet :: IntegerSet(int (&arr) [N]) : set() {
       for (int i = 0; i < N ; i++)
          set [arr[i]] = 1;        
       for (int i = 0; i < 20; i++)
           cout<<i<<"\t"<<set[i]<<"\n";
  }
}

这篇关于在构造函数中传递数组的C ++程序中,执行停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆