Reputation: 385
when I tried to dynamically allocate an array of pointers to char, I accidently added extra parenthesis
char** p = new (char*) [5];
and an error occured
error: array bound forbidden after parenthesized type-id|
I don't quit understand what's wrong and what's the difference between above code and
char** p = new char* [5];
does these parenthesis alter the semantics?
Upvotes: 1
Views: 438
Reputation: 60255
do these parenthesis alter the semantics?
Yes, the new
operator uses a parenthesized argument to trigger "placement new" -- it's expecting what's in the parentheses to point to raw storage.
You give new
the declaration of the object you want to allocate, only without the name, and every declaration begins with a typename.
// I find "inside-out, right to left" to be a helpful rule
char *a[5]; new char *[5]; // no parens, so array of 5 pointers, to char
char (*a)[5]; new char (*)[5]; // pointer to array, of char
That error message isn't one of the more helpful ones ever emitted by a compiler.
Upvotes: 0
Reputation: 1
I think the way your write your code is look like you calling the overloaded version of the 'new' operator that uses to initialize the location of raw memory such as
struct point
{
point( void ) : x( 0 ), y( 0 ) { }
int x;
int y;
};
void proc( void )
{
point pts[2];
new( &pts[0] ) point[2];
}
Upvotes: 0
Reputation: 126777
Parentheses in types can alter the meaning of the declaration; for example, new char * [5]
is an array of 5 pointers to char, but char (* a)[5]
is a pointer to an array of 5 chars.
On the other hand, the type declaration you wrote has no meaning, as the compiler signaled.
For examples about the (messy) C syntax for declarations and how to interpret them, see here, and see here for a C declarations <-> English converter.
Upvotes: 1
Reputation: 254431
does these parenthesis alter the semantics?
No, it alters the syntax from valid to invalid. You can't just put parentheses anywhere you like; they can only go in places where parentheses are allowed, and this isn't one.
Upvotes: 2