c2009l123
c2009l123

Reputation: 61

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

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 > 96) && (ascii < 123)) {

}

This is not working, i would appreciate help

Upvotes: 1

Views: 4681

Answers (5)

Jack
Jack

Reputation: 1438

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

{

}

Upvotes: 1

Murali VP
Murali VP

Reputation: 6417

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.

Upvotes: 0

ACBurk
ACBurk

Reputation: 4428

I believe this will do the trick

int asciiNum = (int)*ascii;

Upvotes: 0

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

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

}

Upvotes: 3

Doug T.
Doug T.

Reputation: 65589

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

 }

Upvotes: 8

Related Questions