Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 675
AppleGrew Avatar asked Feb 26 '26 19:02

AppleGrew


2 Answers

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.

like image 142
xtofl Avatar answered Mar 01 '26 09:03

xtofl


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.
like image 40
unwind Avatar answered Mar 01 '26 09:03

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!