Click here to Skip to main content
13,199,669 members (59,852 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I am quite puzzled by the code below:

char *pchar=new char[2];
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 24-Apr-11 2:02am
Updated 25-Apr-11 2:01am
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
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

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.
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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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];

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.171020.1 | Last Updated 25 Apr 2011
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100