Replacing malloc with new

Hi, I'm trying to replace this line
array = (el *)malloc(realsize*sizeof(el));

with this one
(el *) array = new array[realsize*sizeof(el)]

Is this correct?
nope. You don't need to cast or use sizeof with new:

array = new el[realsize];
thanks man,
in the case of realloc new is also applicable?

like this?:
array = (el *)realloc(array, sizeof(el)*realsize);

array = new [realsize];
????

I'm just playing with malloc, realloc, new and delete, though malloc seems like a good choice (i keep reading its faster but it depends on your application) and since my application is just to see how vector is implemented, malloc and realloc seem the way to go

what do you think?
Thanks firix, i am still reading on the difference between the two
in the case of realloc new is also applicable?


No. new does not have a direct replacement for realloc.

Although you generally don't need to do realloc. If you will need to dynamically size something, it's usually better just to use a vector.

though malloc seems like a good choice (i keep reading its faster but it depends on your application)


Hogwash. there's no reason malloc would ever be faster than new. The only difference between them is typesafety (a compiletime check - doesn't impact performace) and the fact that malloc doesn't call ctors -- which is completely devestating for allocation of any non-trivial type.

since my application is just to see how vector is implemented, malloc and realloc seem the way to go


More hogwash.

malloc has no place in C++. Just use new[].
Awesome info, thanks for everything disch
Topic archived. No new replies allowed.