Re: Why is this working?
jeffmax@gmail.com wrote:
Can anyone explain why the following code works?
#include <iostream>
int main ()
{
char (*p)[];
OK, so 'p' is a pointer to a single-dimensioned array of chars.
p = (char(*)[]) new (char[3]);
So, you're allocating an array of three chars and casting the
pointer to its first element to a pointer to an array of chars.
I am not sure this should work without undefined behaviour.
(*p)[0] = 'c';
You're dereferencing the pointer to the array (and get the actual
array, or a reference to it), then you index within it. You're
getting a reference to the first element of that array. Then you
assign 'c' to it. Should be no problem.
cout << (*p) << endl;
You dereference the pointer to the array, get the array, it is
converted to a pointer to 'char', and printed. Since the rest of
the array is not initialised, it can cause undefined behaviour.
If the second or the third elements of the array just happen to
be zero, you get lucky.
}
The above code will print out 'c'. Why is it that the line
(*p)[0]='c' does not cause a segfault? Isn't it the equivalent of
*(*p).
It is. But (*p) is an array that decays to a pointer if you try to
apply indexing to it.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask