开发者

How to cast a pointer to an int in c ( to get its ascii value )

开发者 https://www.devze.com 2022-12-12 18:04 出处:网络
I have a pointer ( *ascii ) which a pointer to a char and I want it is value as an int in order to make it an if statement like

I have a pointer ( *ascii ) which a pointer to a char and I want it is value as an int in order to make it an if statement like

if ( ascii == 32 || ((ascii开发者_如何学JAVA > 96) && (ascii < 123)) {

}

This is not working, i would appreciate help


Your code is not working because you are checking the value of the pointer (the memory address) not the value of the thing being pointed at. Remember a pointer is an address, you have to dereference it to get the value at that address.

Once dereferenced, you can simply do a comparison with a char type to those values:

 char ascii_char = *ascii;

 if ( ascii_char == 32 || ((ascii_char > 96) && (ascii_char < 123)) 
 {

 }


Just put a * before the variable name

if ( *ascii == 32 || ((*ascii > 96) && (*ascii < 123)) {

}

or just assign it to another variable and use it instead

int a = *ascii
if ( a == 32 || ((a > 96) && (a < 123)) {

}


Why do you go for ASCII value?

Following would be more readable way:

char ascii_char = *ascii;

if ( ascii_char == ' ' || ((ascii_char >= 'a') && (ascii_char <= 'z'))

{

}


I believe this will do the trick

int asciiNum = (int)*ascii;


If you are not referring to comparing just the first char but the number stored in that ascii pointer then use atoi() function to convert the char array to a number and then compare.

0

精彩评论

暂无评论...
验证码 换一张
取 消