【发布时间】: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;这是什么,谁能解释一下?