【问题标题】:In C++ program which passes array in constructor, execution stops在构造函数中传递数组的 C++ 程序中,执行停止
【发布时间】:2013-05-24 03:49:48
【问题描述】:

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

前-

 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;
   }

【问题讨论】:

  • 使用set作为变量名的坏习惯。
  • 为什么你认为 arr 是零终止的?
  • 不改变程序输出/执行。 set 不是关键字。我把它改成了 setArray 虽然 set 看起来更直观,但是问题的答案呢?
  • @Sergey :在带有 != '\0' 条件的 for 循环中,如果您打印“test”,则会打印 7 次。我在stackoverflow上找到了问题的答案..当数组作为参数传递时如何查找数组的长度,因为在这种情况下 sizeof 运算符将返回指针的大小,在我的机器中是 4
  • set [arr[i]] = 1; 这是什么,谁能解释一下?

标签: c++ arrays debugging


【解决方案1】:

arr[i] != '\0' 中,您的数组没有空终止符,因此循环继续,索引元素通过数组末尾。

最佳做法是使用std::arraystd::vector。另一种选择是对您的代码进行以下修复:

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";
  }
}

【讨论】:

  • int a[] = {1,3,4,12,14,15,'\0'} in main.cpp 完成了这项工作!谢谢大家!
  • @ShivaniDhanked:这可能会导致问题,请尝试以下数组:int a[] = {1,3,4,0,14,15,'\0'};。循环将提前停止。
  • 哦,是的,我在发布此评论后很快意识到了这一点。但是循环为什么会打印“测试字符串”7 次,即正确解析为数组长度而不使用终止 null ......不是有比你刚才建议的更简单的出路。我正在寻找最接近我的代码的东西。谢谢
  • 字符串很特殊,它们确实在末尾有一个隐式的空终止符。解决问题的另一种方法是将数组的长度作为第二个参数传递,IntegerSet :: IntegerSet( int arr[], int length) 并循环直到那时:for (int i = 0; i &lt; length ; i++)
  • 谢谢,但是知道它不能那样做,集合是唯一的私有数据成员,所以它可以单独传递给构造函数。
【解决方案2】:

当你将一个数组解析为一个函数作为参数时,它的名字是指数组中第一个元素的地址。因此,在您的情况下,a 是一种 int *。所以你需要将你的构造函数参数更改为 int *

【讨论】:

  • int []int * 与参数的含义相同。
猜你喜欢
  • 1970-01-01
  • 2016-04-03
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多