Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
4.20/5 (5 votes)
See more:
I am quite puzzled by the code below:

char *pchar=new char[2];
pchar[0]=4;
...
int t=pchar[0];

for(int i=0;i<t;t;i++)>
  do sth.
...


pchar[0] is a char, can it be compared with an integer without any previous
action? Is it safe to do so?
Posted
Updated 25-Apr-11 2:01am
v2
Comments
Albert Holguin 24-Apr-11 19:00pm    
not sure why this was voted down, its a legitimate question, my 5
solesonglei 24-Apr-11 23:47pm    
thanks for Albert,I'll pay more attention on my question

Yes, you may assign a char to an int (a char is a signed int 8-bit wide, the promotion to a wider integer type, like int, happens automatically and without complains). It is a bit unusual (and you don't really need it, in the posted example), but there's nothing wrong in that.
:-)
 
Share this answer
 
Comments
Albert Holguin 25-Apr-11 10:25am    
Not that unusual actually... my 5
CPallini 26-Apr-11 3:18am    
Yes, we 'embedded' people, after all, exist.
This depends on the action you want to do:
char type is signed therefore you get negative int, for example "©"==-87.
better you cast:
int t=(int)(unsigned char)pchar[0];

Regards.
 
Share this answer
 
No, this is not safe or even reasonable code. If you wanted an array of int's, you should have said new int[2] instead of new char[2].

However, having said that, you can convert a char to an int, although the compiler might complain; it would be better to cast the char to an int.
 
Share this answer
 
v2
Comments
solesonglei 24-Apr-11 9:36am    
I see ,thx.
Albert Holguin 24-Apr-11 18:59pm    
there's a big difference in new int[2] versus new char[2], 6 bytes worth... people commonly use char's to handle 8bit data, may not be the best practice, but it is common

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900