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 *
You have to cast it to MSG *
yourself.
new
casts it for you
malloc()
takes bytes count as an argument, which means
You have to calculate bytes count yourself (num * sizeof(MSG)
).
You can miscalculate the bytes count (e.g. sizeof(MSG)
vs sizeof(MSG *)
)
new
automatically calculates bytes count for you