【问题标题】:Getting wrong array values获取错误的数组值
【发布时间】:2015-03-24 14:57:05
【问题描述】:

打印数组digitArraytesto 的值显示不正确的值。

Display.cpp

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "display.h"

#define D0 26
#define D1 27
#define D2 28
#define D3 29
#define BL 15
#define BM 16
#define BR 4
#define MI 5
#define TL 10
#define TM 11
#define TR 6
#define DOT 1

int segmentArray[8] = {BL, BM, BR, MI, TL, TM, TR, DOT};
int digitArray[4] = {D0, D1, D2, D3};
int testo[4] = {260, 1,2,3};

//Sets all segments on
void Display::test() {
    std::cout << digitArray[0] << std::endl;
    std::cout << D0 << std::endl;
    std::cout << testo[3] << std::endl;
    std::cout << segmentArray[0] << std::endl;
}

Display.h

class Display {
    public:
        void test();

    private:
        int SegmentArray[8];
        int digitArray[4];
        int testo[4];
};

main.cpp

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "display.h"

int main() {
    Display display;
    display.test();

    return 0;
}

运行这段代码给了我:

35588 (incorrect, varies from time to time and appears to be some adress)
26 (correct)
0 (incorrect)
15 (correct)

【问题讨论】:

  • 你发的sn-p没有问题。请发帖enough code 说明问题。
  • 代码工作正常 - ideone.com/i3qDzI - 问题在别处。
  • 刚刚添加了完整的代码。
  • calcSegments 返回一个指向局部变量的指针。函数返回后,您的数组不会持续存在。要么返回std::array,要么使数组成为静态的。另外,不要将宏用于常量。
  • 我要改变这些东西。但这部分确实有效。

标签: c++ arrays


【解决方案1】:

我测试了你的代码并获得了这个值:

26
3 
26
15

当你写 digitArray[0] 时,你会得到数组中索引 0 的值。 所以在你的情况下是26。 对于第二个输出,您编写 testo[3] 以便获得数组的第四个索引,因此值为 3。 请记住,数组在 C++ 中从索引 0 开始...

重新编译你的代码,也许你最新的修改不会被保存... 您的第一个结果似乎是一个地址。

【讨论】:

  • 我在编辑帖子时弄乱了输出的顺序。我重新编译了很多次,但仍然得到这两个数组的错误值。
  • Display.cpp 中有与 Display 类成员同名的全局变量。在您的“cout”中,使用的是成员而不是全局变量。在成员变量和全局变量之间做出选择。
【解决方案2】:

calcSegments 返回一个指向本地数组的指针,该数组在您尝试访问它时已被销毁。数组是很讨厌的东西,不能(直接)按值返回,所以我建议返回

  • std::array&lt;int, 8&gt; 如果已知大小在所有情况下都是 8
  • std::vector&lt;int&gt; 如果大小可能会有所不同。

【讨论】:

  • 我刚刚删除了完整的 calcSegments 方法并重新编译了所有内容。我仍然得到错误的值。
  • @Rarn34:那你最好把调试器拿出来。或者,如果您希望人们为您调试代码,请将代码缩减为 minimal, self-contained test case
猜你喜欢
  • 2017-04-18
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多