Reputation: 11
i was trying the code of "KEYVIEW1.C − Charles Petzold, 1998 " in visual studio but i encountered an error by this part of the code:
pmsg =(void*) malloc(cLinesMax * sizeof (MSG));
the error is :
Error 1 error C2440: '=' : cannot convert from 'void *' to 'PMSG' d:\win32 projects\win32project8\win32project8\win32project8.cpp 97 1 Win32Project8
can any one help me solving this problem ?
Upvotes: 1
Views: 868
Reputation: 582
The error is caused by (void *)malloc(..)
.
malloc()
doesn't know your variable type (MSG *
) so it returns a typeless pointer (void *
).
Now you want to set a MSG *
to a void *
and that's where the error happens.
MSG *
and void *
obviously aren't the same types.
Don't use malloc()
in c++: Why?, Why?
Code examples:
If you still want to use malloc()
, here is how:
MSG *pmsg = (MSG *)malloc(cLinesMax * sizeof(MSG)); // Allocate Memory
... pmsg[0].member = "blub"; // Do stuff with pmsg
free( pmsg ); // Delete dynamic allocated memory
If you want to use the c++-way, here is how:
MSG *pmsg = new MSG[cLinesMax]; // Allocate an Array of MSG's with size $cLinesMax
... pmsg[0].member = "blub"; // Do stuff with pmsg
delete[] pmsg; // Delete dynamic allocated memory
The c++-way is more readable in my opinion and new
and delete
are safer than malloc
and free
.
Clarification example: http://ideone.com/46twoD
In fact: YOU make less errors with new
and delete
!
malloc()
returns void *
MSG *
yourself.new
casts it for youmalloc()
takes bytes count as an argument, which meansnum * sizeof(MSG)
).sizeof(MSG)
vs sizeof(MSG *)
)
new
automatically calculates bytes count for youUpvotes: 2
Reputation: 33
To remove the error, either use a C compiler; or if you want to stick with a C++ compiler, then you need to explicitly type cast the return value of malloc.
Similar problem is resolved here: Cannot convert from 'void *' to 'node *'
Upvotes: 1
Reputation: 2788
Suggestion
DO NOT use malloc() in C++ programs, prefer using new
or, even better RAII techniques.
If you are still forced to use malloc() for whatever reason, you have to cast the void* returned by malloc() to the receiving variable pointer type, in your case probably:
pmsg = (MSG*)malloc(cLinesMax * sizeof(MSG));
Upvotes: 1