Reputation: 9574
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?
Upvotes: 2
Views: 349
Reputation:
I'd question why you are allocating such a thing in the first place. In C++, a std::vector of std::string is much more likely to be what you need.
Upvotes: 1
Reputation: 399979
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:
x
points at", i.e. 20 times the size of a single char *
pointer.wchar_t **x
this would still work, and not by chance.malloc()
. In C++, you need to cast the return value. In C, you should never do that.Upvotes: 4
Reputation:
New was introduced in C++. Malloc is C.
You shouldnt mix and match them... i.e. dont use delete on something you have used malloc on. Check this article.
Upvotes: 2
Reputation: 41519
Apart from the pointer-syntax mentioned by unwind, it is equivalent: an array of 20 char* will be allocated and deleted in both cases.
C++-adept warning: use std::vector< std::string >
instead :) No memory management needed.
Upvotes: 7