简体   繁体   English

为指针数组动态分配数组

[英]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的指针数组时,我意外地添加了额外的括号

  char** p = new (char*) [5];

and an error occured 并发生错误

error: array bound forbidden after parenthesized type-id| 错误:带括号的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. 例如, new char * [5]是一个包含5个指向char的指针的数组,但char (* a)[5]是指向5个字符数组的指针。

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. 有关声明的(乱)C语法以及如何解释它们的示例,请参见此处 ,并在此处查看C声明< - >英语转换器。

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 我认为你编写代码的方式就像你调用'new'运算符的重载版本一样,用于初始化原始内存的位置,如

   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. 是的, new运算符使用带括号的参数来触发“placement new” - 它期望括号中的内容指向原始存储。

You give new the declaration of the object you want to allocate, only without the name, and every declaration begins with a typename. 你给new希望分配,只有没有名称的对象的申报,每声明使用类型名开始。

// 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. 该错误消息不是编译器发出的更有用的消息之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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