Question

I have an array:

int arr[]={'1','2','4','8','16','32','64','128'};

And I'm calling it with this line:

a=arr[a];

However, I'm not getting the desired output. The input is as expected (I've checked this, it goes from 0-7), but the output comes out as 49,50,52,56,49,51,54,49 depending on the input. What have I done wrong?

EDIT: Quotation marks mean ASCII. Knew I'd missed something simple.

Was it helpful?

Solution 2

The initializers in the array are character literals, not int values so the array will be populated with the numeric value of each character literal (multibyte character literals, such as '32', are permitted but their value is implementation defined, see How to determine the result of assigning multi-character char constant to a char variable?).

To get the desired output use int literals:

int arr[]={1,2,4,8,16,32,64,128};

OTHER TIPS

The output is correct. 49 is the ASCII value of the character '1' which is what you have as the first entry in the array, for example.

In this declaration int arr[]={'1','2','4','8','16','32','64','128'};, you are storing the ascii values as you are declaring them to be character strings. Hence, the values of 49 for 1, 50 for 2,52 for 4, 56 for 8, 49 for 1 of 16, 51 for 3 of 32, 54 for 6 of 64 and 49 for 1 of 128, which is retrieved when you index into the array.

int arr[]={'1','2','4','8','16','32','64','128'}; You should declare your arr array as char instead of int.

The exact reason you are getting numbers instead of characters is that the output library you are using is called with an int parameter. From that, the library understands the data you are giving it should be interpreted and displayed as numbers.

Also, the numbers you are getting are the ASCII or number equivalent of the values in your array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top