What does int nums[5];
do? When I pass nums
to std::cout
, it prints a memory address I think, but I don't understand what the code itself is actually doing when it runs.

- 555,201
- 31
- 458
- 770
-
1You'll want to learn what an *array* is. – Drew Dormann Nov 19 '15 at 02:49
-
1Possible duplicate of [What is array decaying?](http://stackoverflow.com/questions/1461432/what-is-array-decaying) – Nov 19 '15 at 02:51
-
@NickyC: While that answer addresses the question of why `cout` prints a memory address for an array, it does not address the question actually asked here, so I do not think it is a duplicate, just additional useful info. – Remy Lebeau Nov 19 '15 at 02:55
2 Answers
int nums[5];
allocates memory for a static array of 5 int
values.
When you then do std::cout << nums;
, it is actually calling std::cout.operator<<(nums);
While std::cout
has many <<
operators defined for many different type types, it does not have an <<
operator that accepts an int[]
array as input. What it does have is an <<
operator that accepts a const void*
memory pointer as input. It prints the value of the memory address that the pointer is pointing at.
A static array can "decay" into a pointer, in this case to an int*
.
Any type of pointer can be assigned to a void*
. And any non-const
variable can be assigned to a const
variable of compatible type. That is why the compiler does not complain when you call std::cout << nums;
. It is essentially acting similar to std::cout.operator<<((void*)(int*)nums);
behind the scenes.

- 1
- 1

- 555,201
- 31
- 458
- 770
'nums' is an array that holds 5 int type datas.For Example: int nums[5] = {1,2,3,4,5};
if you want to cout nums,you should write your code like this:
for(int index = 0; index < 5; index ++){
std::cout<<nums[index]<<std::endl;
}
but ,if you want cout it's memory address,you should write your code like this:
for(int index = 0; index < 5; index ++){
std::cout<<nums<<std::endl;
nums ++;
}

- 61
- 5