【问题标题】:Console keeps printing hexadecimal instead of contents in the array控制台不断打印十六进制而不是数组中的内容
【发布时间】:2016-01-22 21:41:02
【问题描述】:

我正在尝试创建一个大小为 100 的数组,其中填充了 0。当我去打印该区域时,打印的是:0x7fff5fbff54c。它似乎正在打印该区域的地址,我不确定为什么以及如何解决这个问题,以便它打印出它应该打印的内容。下面是我的代码。

列表.hpp

typedef int ElementType;
const int MAX = 100;
class List
{
   public:
      List();
      bool Empty();
      void InsertAtEnd(ElementType x);
      void Delete(ElementType x);
      void Display();
      int Smallest();
      int Largest();
      int Range();

   private:
      int N;
      ElementType listArray[MAX];

};

列表.cpp

    #include "List.hpp"
    #include <iostream>
    using namespace std;

    List::List() {

        listArray[99] = {0};
    }

    void List::Display() {

        cout << listArray;

   }

main.cpp

    #include "List.hpp"
    #include <iostream>
    using namespace std;

    int main() {

       List list;
       list.Display();
       return 0;
    }

【问题讨论】:

  • 看起来好像你来自 python 编程,print(listArray) 会打印整个数组但是在 c++ 中你不能这样做并且需要编写一个访问每个元素的循环
  • 您正在打印一个指针值,这就是预期的结果。
  • 我对其进行了更改,使其使用 for 循环,现在它打印 0 0 0 0 0 0 0 1606416136 32767 1606422582 @πάνταῥεῖ
  • @Krae 所以你现在正在打印未初始化的值?请提供minimal reproducible example
  • @πάνταῥεῖ 你是什么意思?我已经提供了代码和输出

标签: c++ arrays output


【解决方案1】:

那是因为 listArray 是一个指针,所以你打印的是指针的地址。如果你想打印内容,你需要编写一个循环来遍历每个元素并打印值。

类似:

for (int i=0; i< MAX; ++i)
{
   cout << listArray[i] << ", ";
}

cout << endl;

@πάνταῥεῖ 是正确的。试试这个:

 class List
 {
    public:
       List();
       bool Empty();
       void InsertAtEnd(ElementType x);
       void Delete(ElementType x);
       void Display();
       int Smallest();
       int Largest();
       int Range();

    private:
       int N;
       ElementType listArray[MAX] = {0};

 };

并从您的构造函数中删除初始化

【讨论】:

  • 现在打印 0 0 0 0 0 0 0 1606416136 32767 1606422582 @Rob
【解决方案2】:

你不想循环吗:

查看上一个问题:

loop through an array in c++

【讨论】:

    【解决方案3】:

    你有的代码

    List::List() {
        listArray[99] = {0};
    }
    

    只需在索引99 处初始化listArray 的值。

    要将数组初始化为0,您需要使用构造函数初始化列表:

    List::List() : listArray {0} {
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 2013-03-31
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多