Quote:Original post by MaulingMonkeyQuote:Original post by fpsgamerQuote:Original post by TheTroll
Read 6.3.
"A reference to an object of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the resultant pointer is pointer-to-T. "
theTroll
The key phrase in that quote is "decays to".
Indeed (emphasis added in the original quote). Decays does not mean "is", it means "is implicitly convertable to". This can be an important distinction -- for example, trying to cast a pointer to an array of int:int array[3];int (*ptr_to_array)[3] = &array
into a pointer to a pointer to an int:int ** ptr_to_ptr = (int**)ptr_to_array;// Note that the above won't compile without the explicit cast.
And then using that pointer yields undefined behavior. And no, I'm not talking "in theory", I'm talking about in practice almost certainly having a crash at best:// Compiled with MSVC2008 and executed on a typical x86 box:array[0] = 42; // This works fine, defined behaviorptr_to_array[0] = 42; // This works fine, defined behaviorptr_to_ptr[0] = 42; // This generates an Access violation writing location 0x0000002a (42) // (it tried to treat the integer value stored at array[0] as an address) // (Yes, this statement invoked undefined behavior)
Actually I think there is something wrong with your second example also: you are assigning an int into an array of 3 ints.
It should be ptr_to_array[0][0] =42 or (*ptr_to_array)[0] = 42
As for the 3rd example, it will work if you wrote ptr_to_ptr[0] = (int*)42 right? (just making sure I follow you)
edit: I tried it in g++, and your 2nd and 3rd examples don't compile. When I changed it to my suggestions it worked fine, no access violation.
[Edited by - Iftah on July 28, 2008 3:55:56 AM]