Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
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 24-Apr-11 2:02am
Edited 25-Apr-11 2:01am
thatraja239.8K
v2
Comments
Albert Holguin at 24-Apr-11 19:00pm
   
not sure why this was voted down, its a legitimate question, my 5
solesonglei at 24-Apr-11 23:47pm
   
thanks for Albert,I'll pay more attention on my question
Rate this: bad
good
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.
Smile | :)
  Permalink  
Comments
Albert Holguin at 25-Apr-11 10:25am
   
Not that unusual actually... my 5
CPallini at 26-Apr-11 3:18am
   
Yes, we 'embedded' people, after all, exist.
Rate this: bad
good
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];
Regards.
  Permalink  
Rate this: bad
good
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.
  Permalink  
v2
Comments
solesonglei at 24-Apr-11 9:36am
   
I see ,thx.
Albert Holguin at 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
0 Dnyaneshwar@Pune 604
1 thatraja 370
2 OriginalGriff 319
3 Sergey Alexandrovich Kryukov 241
4 Gihan Liyanage 194
0 OriginalGriff 737
1 Dnyaneshwar@Pune 604
2 Kornfeld Eliyahu Peter 505
3 Sergey Alexandrovich Kryukov 372
4 thatraja 370


Advertise | Privacy | Mobile
Web02 | 2.8.140902.1 | Last Updated 25 Apr 2011
Copyright © CodeProject, 1999-2014
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