'Why is memory adress getting printed instead the values of array in c+.+

When I'm trying to print the values of an array, its memory location is getting printed instead of values. What am I doing wrong?

int main()
{
    int list[3];
    for (int i=0; i<3; i++)
    {   
        list[i] = i;
        std::cout<<list<<std::endl;
    }   
}

OUTPUT: 0x7ffffef79550



Solution 1:[1]

C++ doesn't provide an overload for arrays when using the iostream library. If you want to print the values of an array, you'll need to write a function or find one somebody else has written.

What's happening under the hood is list is decaying to an int*, and that's what you're seeing printed.

Solution 2:[2]

This looks like a typographical error:

std::cout << list

You want to print a specific element of the array, right?

std::cout << list[i]

When printing "the whole array" without index, the pointer to first element is printed (see the other answer for reason).

Solution 3:[3]

std::cout << list << std::endl;

You're printing the array object itself. What do you expect to see? The name of the array identifier? The address of the first element in the array? (actually this is what happens in your case). Or do you expect the array to neatly iterate over it's elements and build a comma separated string of all the values and output it to the stream? If this is what you want, you have to implement it yourself.

template <std::size_t N>
std::ostream& operator<<(std::ostream& out, int (&arr)[N]) {
    std::copy(std::begin(arr), std::end(arr), std::ostream_iterator<int>{out, ", "});
    return out;
}
int main() {
    int arr[] = {1, 2, 3, 4, 5};
    std::cout << arr << std::endl; // Ok, prints "1, 2, 3, 4, 5, ".
}

Solution 4:[4]

You need to dereference the list. Instead of:

std::cout << list << std::endl;

do:

std::cout << *list << std::endl;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 anatolyg
Solution 3 Felix Glas
Solution 4 Hexa