c++ question

Levi Pearson levi at cold.org
Fri Sep 22 19:31:32 MDT 2006


On Sep 22, 2006, at 6:44 PM, Russel Caldwell wrote:

> Sorry about this but this conversation has uncovered an apparent
> misunderstanding on my part about arrays. When I do the following:
>
>     int foo[5] = {1, 2, 3}
>
>     cout << &foo;       //I get an address
>     cout << foo;         //I get the same address
>     cout << &foo[0];   //I get the same address
>     cout << foo[0];     //I get the value stored in the first slot
>
> What this seems to be telling me is that the address of foo[0] is  
> stored at
> the same address as the value of foo[0]. What am I missing?
>

foo is of the type int array.   This means that the memory for it got  
allocated right there on your stack and the compiler knows that 'foo'  
refers to it.  Taking the address of an array variable yields the  
address of the memory block allocated for it.  Evaluating it without  
a subscript also yields the address of the memory allocated for it.   
Subscripting the variable yields the int stored at the given offset  
in the array.  Taking the address of a subscripted array therefore  
yields the address of the int, which, in the case of the first one,  
is the same address as the memory block allocated for the array.

This is all either incredibly nasty or incredibly elegant, depending  
on whether or not you actually like thinking of the world as a single  
big array.

		--Levi 



More information about the PLUG mailing list