I have the following pointer.
char **x = NULL;
x is will point to an array of pointers. So is the following code correct?
x = new (nothrow) (*char)[20];
and we will dealocate it using
delete[] x;
Is
x = (char **) malloc(sizeof(char **) * 20);
and
x = new (nothrow) (*char)[20];
equivalent?
No, that code has syntax errors. The asterisk goes after the type name, to form a pointer to that type. So it’s:
not:
It’s weird that you have this right in the “C-style” example using
malloc(), but not in C++.As many commenters have kindly enough pointed out, there are other issues with the
malloc()and its use ofsizeof, though. But at least it got the type name right. Personally I’m against repeating type names inmalloc()calls if at all possible, so I would write that version like this, to allocate a dynamic array of 20 character pointers:This way:
xpoints at”, i.e. 20 times the size of a singlechar *pointer.wchar_t **xthis would still work, and not by chance.malloc(). In C++, you need to cast the return value. In C, you should never do that.