Learning
Learning

Reputation: 17

Memory Address showing? C++

Not really sure what's going on here, I'm using Clion as my IDE which I don't believe has anything to do with this but I figured I'd add that information. My confusion comes from a function that I wrote

int Arry()
{

int Mynumbers [5] = {10};

    std::cout << Mynumbers;
}

something simple. It should be assigning 5 integers the value of 10. But when I print out Mynumbers I am shown the memory address. Why is this happening, I thought that was what calling pointers was for. Thank you for your time.

Sincerely, Nicholas

Upvotes: 1

Views: 1396

Answers (4)

juanchopanza
juanchopanza

Reputation: 227390

It is a bit complicated, and there are a few issues at play:

  1. std::cout (actually, std::ostream, of which std::cout is an instance, does not have an overload of operator<< that understands plain arrays. It does have overloads that understand pointers.
  2. In C++ (and C) an array name can be used as an expression in a place where a pointer is needed. When there is no better option, the array name will decay to a pointer. That is what makes the following legal: int a[10] = {}; int* p = a;.
  3. The overload that takes a pointer prints it as a hexadecimal address, unless the pointer is of type char* or const char* (or wchar versions), in which case it treats it as a null terminated string.

This is what is happening here: because there isn't an operator<< overload that matches the array, it decays to the overload taking a pointer. And as it isn't a character type pointer, you see the hexadecimal address. You are seeing the equivalent of cout << &MyNumbers[0];.

Upvotes: 4

wally
wally

Reputation: 11002

Some notes:

void Arry()                     // use void if nothing is being returned 
{
    int Mynumbers[5] = {10};    // first element is 10, the rest are 0
    //std::cout << Mynumbers;   // will print the first address because the array decays to a pointer which is then printed
    for (auto i : Mynumbers)    // range-for takes note of the size of the array (no decay)
        std::cout << i << '\t';
}

Upvotes: 2

Unh0lys0da
Unh0lys0da

Reputation: 196

The value of Mynumbers is in fact the adress of the first element in the array.

try the following:

for(int i=0; i<5;i++) {
    cout << Mynumbers[i];
}

Upvotes: 0

ajrind
ajrind

Reputation: 64

In C++, you can think of an array as a pointer to a memory address (this isn't strictly true, and others can explain the subtle differences). When you are calling cout on your array name, you are asking for it's contents: the memory address.

If you wish to see what's in the array, you can use a simple for loop:

for (int i = 0; i < 5; i++)
  std::cout << Mynumbers[i] << " ";

Upvotes: 1

Related Questions