Re: Void pointers
* Marcel M?ller:
pauldepstein@att.net wrote:
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 */
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]="Sample string";
char str2[40];
char str3[40];
memcpy (str2,str1,strlen(str1)+1);
memcpy (str3,"copy successful",16);
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
return 0;
}
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?
ITYM that the expressions effectively are of type 'char*' in this context.
Since that can be easily misinterpreted: the variables str1, str2 and str3 are
themselves of array type, e.g. str2 and str2 are of type 'char[40]'.
But when an array of T is used where a pointer is expected then there is an
automatic conversion to 'T*', producing a pointer to the first element.
In C that conversion always kicks in for use of an array in a run time
expression, although even in C you can do sizeof(str2) and get 40, not e.g. 4.
In C++ the conversion only kicks in where the expected type is a pointer (that
includes a simple indexing expression, and generally all C expressions that
involve arrays, since the point is to keep C compatbility), e.g. there's /no
conversion/ to 'char*' when passing str2 as argument to
void foo( char (&t)[40 ) {}
which among other things means that if you overload foo with various array sizes
then which one's called (if any) depends on the array.
[snip]
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
instead.
And replace printf either by the streaming operators '<<' (ugly) or use
boost::format (similar to printf, but type safe).
Yes. :-)
Cheers,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!