I am working on a program which would really become easier to write if I can use character variables as an index to an array.. for eg. if char_var is a character variable say initialized to 'a'(ascii decimal value = 97), then array1[char_var] should refer to array1[97] element.

I wrote a snippet to test this

{
      int array[200],i;
      for (i=0;i<200;i++)
      {
          array[i]=i;
      }
      char c='a';
      cout<<array[c];
      getch();
}

It works the way I intend it to. However I was wondering if it could be compiler dependent in any way? also could you suggest any other way to write the code.I would like to avoid using atoi function. Thanks in advance !

Declare an unsigned int variable and cast the char variable from char to unsigned int:

{
    int array[200],i;
    for (i=0;i<200;i++)
    {
        array[i]=i;
    }
    char c='a';
    unsigned index = (unsigned)c;
    cout<<array[index];
    getch();
}

It is perfectly ok to use char variable as an index to an array -- in fact it is very handy thing to do at times. For example lets say you need to count the number of occurrences of each letter in a sentence. To do that just loop through the string and use each character as the index into an int array. No typecasting is needed because type char is already an integer (one byte integer).

int count[255] = {0};
std::string sentence = "Hello World";

for(int i = 0; i < sentence.length(); i++)
{
   ++count[sentence[i]];
}

for(int i = 0; i < 255; i++)
{
   if( count[i] > 0)
   {
      cout << "Letter " << (char)count[i] << ": " << count[i] << '\n';
   }
}

And now I've gone and done someone's homework.

Edited 6 Years Ago by Ancient Dragon: n/a

OP>>I would like to avoid using atoi function.
You can use stringstream for converting between strings and other types, in the same way you take input from cin and output to cout.

For the rest, I think AD answered pretty well.

Thanks everyone
@fisrtPerson : I need an 2D array to store the bits of ascii characters..such that the index is a simple function of the ascii character.. so if I use array[a][0]..I get the MSB of the character 'a' ..

That will not give you the MSB of a character. Use the shift << operator to get that. Here is a tutorial about bit operators

Edited 6 Years Ago by Ancient Dragon: n/a

This article has been dead for over six months. Start a new discussion instead.