0

我的代码有什么问题?我想打印出数组,但是当我尝试这样做时,它似乎打印出一个地址。

#include <iostream>
#include <ctime>
#include <stdlib.h>

using namespace std;

int main ()
{
    srand(time(NULL));

    int array[9]= {0};

    for (int i=0;i<=8;i++)
    {
        array[i]= (rand()%101);
    }

    cout<< array;

    system ("PAUSE");
    return 0;
}
4

5 回答 5

4

You can't just cout an array. Arrays are not cout-able. Whenever you successfully cout something of type T, it means that there's a dedicated overloaded << operator designed specifically to cout values of type T. And there's no dedicated << operator for cout-ing arrays (aside from strings). For this reason the compiler chooses the closest match for the given argument type: a << operator for pointers. Since arrays are convertible to pointers, that << is applicable here.

If you want to cout the values of all elements of your array, you'll have to either cout them manually, one by one, or use some standard algorithm that can do it for you. For example

std::copy(array, array + 9, std::ostream_iterator<int>(std::cout, " "));
于 2012-04-18T04:25:58.083 回答
2

您需要执行一个循环来单独输出每个数组元素。

问题是 C++ 并不总是知道数组的大小,所以它不能像你期望的那样默认输出整个东西。

于 2012-04-18T04:17:02.560 回答
1

您需要遍历数组并打印每个元素,就像您在每个索引处分配值的方式一样。由于数组衰减到指向序列中第一个元素的指针,因此您将获得地址。

于 2012-04-18T04:17:11.297 回答
0

C++ decays array type to a pointer type when the value is passed as argument to a function. C++11 has std::array (and TR1 specifies std::tr1::array) which retains the size of the array. Here is your example modified to use std::array:

#include <array>
#include <iostream>
#include <ctime>
#include <stdlib.h>

template<typename T, std::size_t N>
std::ostream& operator<< (std::ostream& ostm, const std::array<T, N>& a)
{
  for (auto const& x : a)
    ostm << x << ' ';

  return ostm;
}

int main ()

{
    srand(time(NULL));

    std::array<int, 9> array;
    for (auto& x : array)
        x = rand() % 101;

    std::cout<< array << std::endl;
}
于 2012-04-18T04:26:32.280 回答
0

std::cout没有重载int array[9],因此它衰减为指针 ( int*),这就是您将看到的显示内容(类似于0x7fffe47142d0)。

要单独打印int数组中的 s,您将需要使用循环构造(例如for用于填充数组的 - 循环)并依次发送每个ints ,可能带有一些空格来格式化它们。std::cout

一旦掌握了 C++ 及其标准库的窍门,您可能想研究如何使用std::copy().

于 2012-04-18T04:25:27.710 回答