I found a code that computes the execution time of merge sort. I'm getting an error that says "Cannot convert void to int" . And I'm getting the error from the part of this code that says x = malloc(n * sizeof (int));
x = malloc(n * sizeof (int));
Since this question is tagged with C++, I recommend a completely different solution: Embrace the power of C++ and use a std::vector
.
std::vector<int> descriptiveNameHere(n);
This approach frees you from having to manually manage the memory allocation. When the vector
is allowed to go out of scope the storage will automatically be freed.
C++ compilers are more strict than C compilers. Therefore not all C code will compile using a C++ compiler, so you shouldn't use a C++ compiler if you are not using any C++ feature.
malloc
returns a void *
so you must cast it to the corresponding type, provided that you are using a C compiler:
Type * x = (Type *) malloc (sizeof(Type));
But if you must use C++ and malloc, then like mentioned in the comments, the C-style cast should be a last resort and you should rather use static_cast
Type * x = static_cast<Type *>(malloc(sizeof(Type)));
You should cast the malloc like this.
x = (int *)malloc(sizeof(int) * n)
because malloc just return void pointer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.