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 !

Recommended Answers

All 6 Replies

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.

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.

Is there a certain reason why you are doing this? What are you trying to solve?

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.