Home > Software engineering >  Why does casting an array of charcters return a long instead of ASCII value?
Why does casting an array of charcters return a long instead of ASCII value?

Time:05-11

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

CodePudding user response:

char inputCharacter[10]; is decayed as a pointer (sizeof() operator is an exception). Then, you are type-casting it to int, hence its address is printed instead of its ASCII value.

To get ASCII value, you need to de-reference it like:

int ASCII_0 = (int)inputCharacter[0];
.
.
.
int ASCII_9 = (int)inputCharacter[9];

Or, better use a loop.

Edit:

You can get the size of inputCharacter, using sizeof() operator.

size_t len = sizeof(inputCharacter) / sizeof(inputCharacter[0]);

CodePudding user response:

With char inputCharacter[10], inputCharacter is an array.

When an array is used, as in (int) inputCharacter, the array is converted to the address of the first element*1. It is like (int) &inputCharacter[0]. That address, which may be wider than an int, is converted to an int, not a long as in the question. In OP's case, that result was 5896032. The address has nothing to do with the content of the array. Expecting 97 is not supported.


Tip: save time and enable all warnings....

char inputCharacter[10];
scanf("%c", &inputCharacter);

... may generate a warning like

warning: format '%c' expects argument of type 'char *', but argument 2 has type 'char (*)[10]' [-Wformat=]

This hints the something is amiss.


*1

Except when it is the operand of the sizeof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type “array of type” is converted to an expression with type “pointer to type” that points to the initial element of the array object and is not an lvalue. C17dr § 6.3.2.1 3

  •  Tags:  
  • c
  • Related