AppleGrew
AppleGrew

Reputation: 9574

Am I using new operator correctly?

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

Answers (4)

anon
anon

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

unwind
unwind

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:

  1. Should be read as "20 times the size of whatever x points at", i.e. 20 times the size of a single char * pointer.
  2. Contains the magical constant 20 in one place only.
  3. 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.
  4. 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.

Upvotes: 4

user110714
user110714

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

xtofl
xtofl

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

Related Questions