[openbeos] Re: Largely Offtopic C/C++ question about pointers

  • From: OpenBeOS.20.magnum@xxxxxxxxxxxxxxx
  • To: openbeos@xxxxxxxxxxxxx
  • Date: Thu, 28 Jul 2005 20:44:11 EST

I'm on the digest list, so maybe someone's answered this better than me.

Re example 1:
The first printf shows the same value for 'element' and '*element' because the 
compiler knows that 'element' points to a t_Array.  The raw value contained in 
the memory allocated on the stack for 'element' is the memory address of the 
beginning of 'array', so this is the output when printing 'element'.  But when 
you dereference 'element' you get an array, and when passing arrays to 
functions C/C++ passes the address of the array.  This is why printf prints the 
same values for 'element' and '*element'.

Note that if you printed out &array you would get the same value.  'array', 
'&array', and '&array[0]' are all equivalent.

The second printf prints the result you expect for array[9] (i.e. 321), the 
same thing for (*element)[9] because 'element' points to 'array', but 'element' 
itself is just a single pointer, so if you dereference the memory 9 spots after 
what it points at (which is what 'element[9]' does) you get undefined data.


Re example 2:
The function fails to compile because to the compiler, Array is a pointer, not 
an array.  Taking the pointer of Array returns a pointer to the 'Array' 
argument to the function, not the address of the array itself.  This time, you 
get different values if you printf("Array = %p, &Array = %p\n", Array, &Array);

Change the parameter to a reference and it works, i.e. 
    void function(t_Array& Array)
    {
        t_Array *ptrArray[] = {&Array};   //this works
    }



Re example 3:
Like I said before, &Array within the function is a pointer to an integer, so 
Array and &Array are different, whereas they are the same in the scope where 
Array is actually allocated.  Change it to a reference and it works as you 
expect.




Note that when you declare an array,  say 'int array[10]', space for 10 
integers is allocated on the stack.  'array' is treated as a pointer to the 
start of the array, but no space is allocated for any pointer.  So &array is 
kind of meaningless, and it's just the same value as 'array'.  If you declare a 
pointer, space is allocated on the stack for the pointer, so 'pointer' and 
'&pointer' are both meaningful, and different.  When you pass an array to a 
function, you are passing the pointer to the start of the array to the function 
as a parameter which gets put on the stack.  So taking the address of the array 
within the function takes the address of the parameter on the stack.

HTH

Other related posts: