【问题标题】:2D-Array deletes elements itself when new elements get stored [closed]当存储新元素时,2D-Array 会自行删除元素 [关闭]
【发布时间】:2019-02-06 20:44:19
【问题描述】:

编辑:我没有用正确的大小初始化数组。我应该使用 8 而不是 7。我必须知道数组从 0 开始计数,但是在初始化时不要!

我有一个二维数组 storage[x][y] 并希望为每个 x 值存储 8 个不同的 y 值。出于某种原因,我可以读出数组中的特定位置,例如 [48][7] 并且在填充数组中的其他空格后,[48][7] 的值发生了变化,即使我从未碰过它。

int storage[127][7];

void store(){
 storage[48][0] =0b01111110;
 storage[48][1] =0b01111110;
 storage[48][2] =0b11100011;
 storage[48][3] =0b11010011;
 storage[48][4] =0b11001011;
 storage[48][5] =0b11000111;
 storage[48][6] =0b01111110;
 storage[48][7] =0b01111110;


   Serial.println(storage[48][7], BIN); // returns 01111110

 storage[49][0] =0b00000000;
 storage[49][1] =0b11000001;
 storage[49][2] =0b11000001;
 storage[49][3] =0b11111111;
 storage[49][4] =0b11111111;
 storage[49][5] =0b00000001;
 storage[49][6] =0b00000001;
 storage[49][7] =0b00000000;

   Serial.println(storage[48][7], BIN); // returns 0
}

根据我存储值的顺序,其中一些会相互删除。

为什么我会突然丢失数据?

【问题讨论】:

  • 请创建一个minimal reproducible examplestorage的类型是什么?
  • 我们不知道storage 是什么。
  • 抱歉……现在好点了吗?
  • 对于数组int storage[7],您可以访问的最大索引是6
  • int storage[127][7]; -- 这是一个越界访问:Serial.println(storage[48][7] ,BIN);。数组索引从 0 开始,一直到 n-1,其中 n 是条目的总数。

标签: c++ c arrays multidimensional-array arduino


【解决方案1】:

您正在定义一个行大小为7 的二维数组,但您访问的是单行的 8 个元素:

 int storage[127][7];

 storage[48][0] =0b01111110;
 ...
 storage[48][7] =0b01111110;

请注意,0..7 实际上是 8 个元素,而不是 7。所以您必须将 storage 定义为...

 int storage[127][8];

现在可以讨论int storage[127][7];storage[48][7] =0b01111110 是否是未定义的行为;

然而最可能的行为是storage[48][7] 映射到与storage[49][0] 相同的内存地址。因此,当您分配storage[49][0] =0b00000000; 时,您“也”写信给storage[48][7],它将变为0b0000000

【讨论】:

    猜你喜欢
    • 2012-07-10
    • 2012-10-17
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    相关资源
    最近更新 更多