Search code examples
c++new-operatordynamic-arraysdynamic-allocation

syntax of operator new[] while creating an array of pointers


I have problems while using new[] operator while creatin an array of pointers to char. Since char* is the type I want my elements to be of, I use parentheses to surround it, but it doesn't work:

char **p = new (char *)[vector.size()];

but when I get rid of parentheses it works:

char **p = new char *[vector.size()];

Why does the latter one work?


Solution

  • This is a result of "declaration follows use". char **p; can be read as "if I dereference p twice, I will get a char". (char*) *p does not have a type on the left, and gets parsed as an expression meaning: "dereference p and cast the result to a pointer to char".

    When char ** gets used as a type name on its own, a similar convention holds. (char*) * does not parse as a type-name at all, but as an expression (because there is no type at the left).