Thursday, August 23, 2007

Can i cast char* to a unsigned char* or vice versa ?

No boss , we can not cast char* to a unsigned char* or vice versa.
The reason is , lets first understand static_cast .

Few points about stati cast listed below
1) Only allowed for conversions which the compiler can check
2) we can not use static_cast to a pointer to a non-pointer
3) we can not use static_cast to remove constness(orvolatileness)
4) we can not use static_cast from a virtual base class
5) Static_cast is only for related types.pointer type (remember pointer type, it works fine for general primitive data type i.e int,char ,float)

So here Char* and unsigned char* are two unrelated pointer types. One more thing ,here one of the pointer is void * then we can do it.
Lets have an example,
#include
using namespace std;


void uchar_f1(unsigned char *x)
{
cout<<"uchar_f1 "<< x <<"\n";
}

void char_f1(char *x)
{
cout<<"char_f1"<< x << "\n";
}int main()
{
unsigned char uc[]={ 'A' , 'B' , 'C' };
uc[3]='\0';
char c[]={ '1' , '2' , '3'};
c[3]='\0';
uchar_f1(uc);
char_f1(c);
uchar_f1(static_cast(c));

}

If we write uchar_f1(static_cast(static_cast(c)));

So this will work.
Cheer,
sahu

2 comments:

srdash said...

hi!
during blog search i noticed your blog. but, alas! i couldn't understand your language. but, belive me it's interesting. anyway, plz add some emotions to your posts.

Haramohan Sahu said...

Hi ,
Thanks for your comment. While posting coment, there may be some typo. Or i have to adjust the HTML Tags. But my concerne is about your doubt. What exactly your doubt. What exactly you could not understand.
Please post me your doubt to my personal email id.
hara.sahu@gmail.com