简体   繁体   中英

dynamic allocation of array for array of pointers

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?

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.

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.

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];
   }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM