Divij Jain
Divij Jain

Reputation: 113

Using characters as indices in arrays

#include<iostream>
using namespace std;
int main()
{
    int arr[128];
    arr['a'] = 101;
    cout<<arr['a'];

    return 0;
}

So i was experimenting around and found that characters can be used as indices in arrays instead of conventional whole numbers. This program gives the correct output i.e 101 which is correct.

But how does this all work? Like in terms of space allocation and reference to that element.

Questions:

  1. 128 blocks of int were declared which is a total of 512 bytes. How does the program store '101' in a char block i.e in a placeholder 'a' which is char? What does space allocation look like?
  2. Why doesn't this program work when I reduce the number of indices of array below 128?
  3. How does program refer to '101' through 'a' since this isn't a map but an array?

Upvotes: 2

Views: 315

Answers (2)

Bathsheba
Bathsheba

Reputation: 234715

'a' is a char type with an implementation defined numeric value (depends on the character encoding used on your platform: in ASCII, it's 97).

That numeric char is used in the evaluation of arr['a']. If you're fortunate, that will give you an element of the arr. If the value is outside the bounds of arr then the behaviour of the program is undefined.

Upvotes: 8

Mureinik
Mureinik

Reputation: 311468

chars are just smaller ints with a fancy way of printing them. A char in fact holds the ASCII value of the character it represents. a has the ASCII value of 97, so your snippet is in fact equivalent to:

int arr[128];
arr[97] = 101;
cout<<arr[97];

Upvotes: 4

Related Questions