Question

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?

Was it helpful?

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).

OTHER TIPS

char *p = new char[10]; dynamically allocates a memory block for an array of size of 10 chars and returns the address of its first element which is then stored into p (making p to point to the beginning of this memory block).

In this case, the new keyword is followed by an array type specifier, you specify the type:
char **p = new char*[10]; - type in this case is char*, not (char*). Check operator new[]

You are probably confused because of C-style malloc syntax where the type of its return value is always void*, which can be cast to different type so that you can dereference it. That's the situation where you use (char*) syntax (C-style type cast): char *p = (char*) malloc(10);
Although note that in C this cast is redundant: Do I cast the result of malloc?

Note that memory that was allocated by using new[] should be freed by calling delete[] and memory allocated by malloc should be freed by free.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top