【问题标题】:Strange behavior from class array类数组的奇怪行为
【发布时间】: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&gt;&gt;11)&amp;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++ 的工作方式。您只能说该程序可能会或可能不会做任何事情。
  • 您肯定会遇到未定义的行为。

标签: c++ arrays class boolean


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    数组边界检查不在 C 风格的数组上进行(或者实际上在 C++ 风格的std::array&lt;&gt;s 上,除非你使用at 成员函数)。如果你想要边界检查,你应该使用std::vector&lt;&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-10
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 2012-01-17
      • 2017-12-02
      • 1970-01-01
      相关资源
      最近更新 更多