【发布时间】:2016-08-13 08:10:27
【问题描述】:
这是我的课:
class counters {
// variables
public:
bool isUsed;
int counterNumber;
int eventType;
char eventDescriptor[256];
// methods
public:
counters();
void setCounterNumber(int counterNumber);
void setEventType(int eventType);
void setEventDescriptor(const char* eventName );
};
这是我的类的构造函数:
counters::counters()
{
isUsed=true;
counterNumber=0;
eventType=0;
strcpy(eventDescriptor,"");
}
这是我对数组的声明:
printf("There are %d counters\n",numberOfCounters);
counters pCounters[numberOfCounters];
int i;
for (i=0;i<9;i++)
printf("%d: Is this valid: %d\n",i,pCounters[i].isUsed);
上面设置了变量numberOfCounters=(rval>>11)&31;,在这种情况下为6。我检查计数器是否正在使用,如果是,我会做一些有用的工作。我的问题是,当我循环检查它是否被使用/为真时,它允许我访问无效的数组元素并返回正整数,这被解释为真,使我的测试看它是否使用无效。我知道一定有一些我不理解的东西,否则我的代码会起作用。尝试访问范围之外的数组元素时,我不应该收到错误吗?
输出:
There are 6 counters
0: Is this valid: 1
1: Is this valid: 1
2: Is this valid: 1
3: Is this valid: 1
4: Is this valid: 1
5: Is this valid: 1
6: Is this valid: 160
7: Is this valid: 0
8: Is this valid: 0
【问题讨论】:
-
如果你知道数组的大小是
numberOfCounters为什么不将它用于for循环的上限? -
程序从一个可能因系统而异的寄存器中获取 numberOfCounters。我原来的循环使用了这个:
while( pCounters[i].isUsed == true ),但我遇到了一些意想不到的行为,这个 for 循环是我试图理解原因。 -
“当我尝试访问范围之外的数组元素时,我不应该得到一个错误吗?”不,这不是 C++ 的工作方式。您只能说该程序可能会或可能不会做任何事情。
-
您肯定会遇到未定义的行为。