Re: Void pointers
This code comes from cpluplus.com
What a shame. It does not contain even a single character that makes use
of C++. It is C code.
/* memcpy example */
int main ()
char str1="Sample string";
memcpy (str3,"copy successful",16);
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
I'm sure it's ok but I'm concerned about the fact that memcpy takes
void* (and const void*) parameters.
Why is it unnecessary to cast str1, str2 and str3 to type char* before
the final printf statement?
? - they /are/ of type char*, so why you want to cast?
memcpy copies memory. No less, no more. And for PODs this is usually
It does not change the type of variables. How should it, since the type
is compile time information (in C) and memcpy operates at runtime.
For example, I read this on another website: "One of the problems with
using void * is that as soon as you convert something to a void * all
information about what type of thing the pointer points at is lost.
There is absolutely _no_ guarantee that the pointer type the void * is
cast back to matches that from which it was created."
No one casts a void* to something else in your code. Except the internal
cast to char* in the C runtime at memcpy, of course.
But, to me, the above code seems to assume that a void pointer points
There are no void pointers in the code, except for the ones in the C
All assumtions made by the above code are satisfied. And there are many.
E.g. that the arrays str2 and str3 are at least as large as str1.
If you want an advice: throw this code away and forget about it. No C++
application should contain code like that. Dealing with raw memory is
known to be fault-prone, and C++ has dozens of ways to avoid that.
In particular do not use char*. It is likely to become the next
generation virus remote installer. Simply don't do that. Use std::string
And replace printf either by the streaming operators '<<' (ugly) or use
boost::format (similar to printf, but type safe).