views:

207

answers:

4

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?

+4  A: 

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.
unwind
You're a better parser than me!
xtofl
Although he doesn't use it entirely correctly because he is creating an array of 20 char*s not 20 char**s. Not that the 2 are different sizes or anything.
Goz
@unwind My bad. I simply overlooked that I wrote (char*) instead of (*char).<br/>@Goz I didn't get what u wanted to say. Here x[i] will point to (char*) poniters, each of which is a varied length string. Hope my declaration is correct.
AppleGrew
exactly ... x[i] will point to a char* but you are allocating 20 char**s. Its not really a problem because sizeof( char* ) and sizeof( char** ) are the same. Just "strictly" you ought to be malloc'ing 20 char*s :)
Goz
What Goz says. The rule of thumb for malloc is that the "sizeof" expression used in the parameter should have one less star than the type of the variable the result is assigned to. So the malloc line is wrong. Since sizof(char*) == sizeof(char**) in any normal environment it works anyway.
Steve Jessop
+7  A: 

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.

xtofl
+2  A: 

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.

Chalkey
+1  A: 

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.

anon