gpt4 book ai didi

c++ - 来自类数组的奇怪行为

转载 作者:行者123 更新时间:2023-11-28 02:08:03 25 4
gpt4 key购买 nike

这是我的课:

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。我检查计数器是否正在使用,如果是,我会做一些有用的工作。我的问题是,当我循环检查它是否被使用/是否为真时,它允许我访问无效的数组元素并返回正整数,这被解释为 true 使我的测试看它是否被使用无效。我知道一定有一些我不理解的地方,否则我的代码就可以工作了。尝试访问范围外的数组元素时,我不应该出错吗?

输出:

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

最佳答案

不一定,您只能说,当访问索引大于大小的元素时,会导致未定义的行为。参见 http://www.cplusplus.com/reference/array/array/operator[]/了解更多信息。

关于c++ - 来自类数组的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36747337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com