memcpy char* to unsigned char *

H

hs

Is the following correct?

void foo(int len, char* val)
{
..
..
..
unsigned char* string = (unsigned char*) new char [ len];
memcpy(string, val, len);
..
..
..
}

memcpy takes void*, val is char* but string is unsigned char* ??

Thanks
hs
 
J

Jack Klein

Is the following correct?

void foo(int len, char* val)
{
.
.
.
unsigned char* string = (unsigned char*) new char [ len];
memcpy(string, val, len);
.
.
.
}

memcpy takes void*, val is char* but string is unsigned char* ??

Any type of pointer to object in C++ may be explicitly converted to
pointer to void without a cast. The prototype of memcpy() in scope
causes the compiler to perform this cast automatically.

Unsigned char can safely hold any value from a signed char, so there
is no problem there.
 
J

John Harrison

Is the following correct?

void foo(int len, char* val)
{
.
.
.
unsigned char* string = (unsigned char*) new char [ len];
memcpy(string, val, len);
.
.
.
}

memcpy takes void*, val is char* but string is unsigned char* ??

Thanks
hs

It legal but I'd question the need to make a string of unsigned char. I
have seen scores of programs which mix unsigned char* and char* resulting
in hundreds or thousands of unnecessary casts, making the program hard to
read and hard to maintain. Generally I would advise creating a string of
char, and the only converting to unsigned char* at the point where you
really need to do that conversion, I find this minimises need for casting.

But if you really need to create an string of unsigned char why did you
write

unsigned char* string = (unsigned char*) new char [ len];

instead of the more obvious

unsigned char* string = new unsigned char [ len];

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top