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

Time:05-12

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:

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

CodePudding user response:

Actually, you are printing the base address (&) of the first element of inputCharacter, which is the 0th element.

The address of a variable is of type size_t, but you are using "%i" format specifier in printf(). Correct format specifier to addresses is "%p".

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.

Converting char array to int array:

int ASCII_vals[10] = {};
for(int i = 0; i < sizeof(inputCharacter)/sizeof(inputCharacter[0]); i  )
{
    ASCII_vals[i] = inputCharacter[i];
}

Edit:

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

int len = sizeof(inputCharacter) / sizeof(inputCharacter[0]);
  •  Tags:  
  • c
  • Related