No, that code has syntax errors. The asterisk goes after the type name, to form a pointer to that type. So it's:
char*
not:
*char
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 of sizeof
, though. But at least it got the type name right. Personally I'm against repeating type names in malloc()
calls if at all possible, so I would write that version like this, to allocate a dynamic array of 20 character pointers:
char **x;
x = malloc(20 * sizeof *x);
This way:
- Should be read as "20 times the size of whatever
x
points at", i.e. 20 times the size of a single char *
pointer.
- Contains the magical constant 20 in one place only.
- Doesn't repeat any part of the type, if you were to change to
wchar_t **x
this would still work, and not by chance.
- Is written in C, since I felt that is more natural when discussing
malloc()
. In C++, you need to cast the return value. In C, you should never do that.