I have the following code below,
std::complex<double>** x;
x = calloc(10,sizeof(complex <double> *));
This code failed to compile with the following error message.
error: invalid conversion from 'void*' to 'std::complex<double>*' [-fpermissive]
How can I successfully compile? Why does this code fail to compile?
In C++, void *
doesn't automatically cast to other pointers (unlike in C). So if you use malloc
and the family in C++, you need to cast the result yourself.
However, you should note that malloc
doesn't understand C++'s constructors. So if you want to allocate a C++ object (not a C struct for example, or more precisely a POD), you should use new
(and delete
/delete[]
correspondingly) which correctly takes care of constructors and destructors.
Alternatively, you can use one of the many structures provided by the standard library, such as std::vector
.