T
Tomás
The following works as expected:
unsigned* p_number = new unsigned;
*p_number = 5;
delete p_number;
However, the following won't compile:
unsigned (*p_numbers)[5] = new unsigned[5];
(*p_numbers)[0] = 5;
(*p_numbers)[1] = 6;
delete [] p_numbers;
My compiler gives me the following error:
cannot convert `unsigned int*' to `unsigned int (*)[5]'
"new" is returning an expression of type "int *" rather than "int (*)[5]".
My first question is, Why did they make it so? I don't see the rationale.
Secondly, does the Standard explicitly specify that "new" returns a pointer
to the first element?
Thirdly, how do you somehow turn it into a pointer to an array? Is the
following valid (I've made it verbose for clarity):
unsigned* p_first_number = new unsigned[5];
void* p_temp = p_first_number;
unsigned (*p_numbers)[5] = static_cast<unsigned (*)[5]>( p_temp );
(*p_numbers)[0] = 5;
(*p_numbers)[1] = 6;
delete [] p_first_number;
I've used a "void*" in the above rather than using "reinterpret_cast".
So is there a pefectly legal way to get a pointer/reference to an array (for
something allocated using "new")?
-Tomás
unsigned* p_number = new unsigned;
*p_number = 5;
delete p_number;
However, the following won't compile:
unsigned (*p_numbers)[5] = new unsigned[5];
(*p_numbers)[0] = 5;
(*p_numbers)[1] = 6;
delete [] p_numbers;
My compiler gives me the following error:
cannot convert `unsigned int*' to `unsigned int (*)[5]'
"new" is returning an expression of type "int *" rather than "int (*)[5]".
My first question is, Why did they make it so? I don't see the rationale.
Secondly, does the Standard explicitly specify that "new" returns a pointer
to the first element?
Thirdly, how do you somehow turn it into a pointer to an array? Is the
following valid (I've made it verbose for clarity):
unsigned* p_first_number = new unsigned[5];
void* p_temp = p_first_number;
unsigned (*p_numbers)[5] = static_cast<unsigned (*)[5]>( p_temp );
(*p_numbers)[0] = 5;
(*p_numbers)[1] = 6;
delete [] p_first_number;
I've used a "void*" in the above rather than using "reinterpret_cast".
So is there a pefectly legal way to get a pointer/reference to an array (for
something allocated using "new")?
-Tomás