I am trying to cast an array of characters to int
(or the corresponding ASCII value), when I try to convert a single char
to int
works fine but when I try to do it with an array it doesn't quite work.
Why is that? What am I doing wrong?
This is an example of a single char
to int
:
char inputCharacter;
int ASCIIValue;
scanf("%c", &inputCharacter);
ASCIIValue = (int) inputCharacter;
printf("%i", ASCIIValue);
Input: a
Output: 97
This is an example of a char
array to int
:
char inputCharacter[10]
int ASCIIValue;
scanf("%c", &inputCharacter);
ASCIIValue = (int) inputCharacter;
printf("%i", ASCIIValue);
Input: a
Output: 5896032
Expected Output: 97
Actually, you are printing the base address (
&
) of the first element ofinputCharacter
, which is the 0th element.The address of a variable is of type
size_t
, but you are using"%i"
format specifier inprintf()
. Correct format specifier to addresses is"%p"
.To get ASCII value, you need to de-reference it like:
Or, better use a loop.
Converting char array to int array:
Edit:
You can get the size of
inputCharacter
, usingsizeof()
operator.