cast pointer to different type, what is the impact?

W

wenmang

Hi, all:
I try to understand whether it is a portable to cast a pointer type,
e.g.,
char *ptr = char array[10]; -- a buffer
unsigned char *uptr = ptr;
:
:
function(uptr); -- execute a function that takes unsigned char * as
arg

What is the impact for such cast? is it safe to do this for
memory(buffer) manipulation?
Thanks.
 
R

Ron Natalie

wenmang said:
What is the impact for such cast? is it safe to do this for
memory(buffer) manipulation?
Thanks.

You have to reinterpret_cast it, unsigned char* and char* are distinct types.

In this case, it is safe. unsigned char and char (and signed char for that matter)
are required to be compatible.
 
T

tom_usenet

Hi, all:
I try to understand whether it is a portable to cast a pointer type,

It depends on the pointer types.
e.g.,
char *ptr = char array[10]; -- a buffer
unsigned char *uptr = ptr;

Well, obviously you need a cast there (a reinterpret_cast).
function(uptr); -- execute a function that takes unsigned char * as
arg

What is the impact for such cast? is it safe to do this for
memory(buffer) manipulation?

It is generally fine to cast char* to unsigned char* and back again.
Other casts generally aren't fine, but you can reinterpret_cast any
pointer to unsigned char* if you just want to examine or copy the
bytes making up the object pointed to.

Tom

C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
 

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

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top