Need explanation regarding array access

I am learning C++ independently from the tutorial.pdf from this site, and up to this point it has been going great, but I have encountered something I cannot understand in the section on arrays:

"Some other valid operations with arrays:
billy[0] = a;
billy[a] = 75;
b = billy [a+2];
billy[billy[a]] = billy[2] + 5;"

I understand the first line; assigning the value of variable a to the first element of the array billy. I am completely lost after this because the tutorial does not explain what billy[a] means. it looks like it is accessing the a element of billy but that is impossible because there is no a element, only billy[0] billy[1] billy[2] billy[3] and billy[4]. What am I missing here?
you can write, for example,

billy[0] = 10;

this can be rewritten using a variable for the index

int i = 0;

billy[i] = 10;

So instead of the integer literal that denotes the index value you can use a variable that will have this value.

So for example you could write

int i = 10;

billy[i] = i; // b[10] = 10;

That is any integral expression can be used to set the index. For example

int i = 10;

billy[ i / 2 ] = i * 2; // billy[5] = 20;



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main()
{
    int billy[] = {1,2,3,4,5,6,7,8,9,0};
    int a;

    std::cin >> a;

    if(a > 0 && a < 10)
    {
        std::cout << billy[a] << " - Current value of billy[a]" << std::endl;
        billy[a] = 75;
    }
    else
        std::cerr << "You entered an invalid array location" << std::endl;

    std::cout << billy[a] << std::endl;

    return 0;
}


I think that should explain it.
Last edited on
I'm sorry, I just started yesterday and I'm not quite sure I get what your saying. Are you saying that the array can be accessed by a variable with a value that corresponds to the variables index number? sorry if i said that wrong, I am not quite sure on what words to use

if a = 4 then billy[4] and billy[a] would be the same?
You are right. In fact the two records

billy[4] = 0;

and

int a = 4;
billy[a] = 0;

are equivaloent.

You are already using variables for example to name the array. The same way you can use integral variables as indexes instead of hard-coded integral literals.
Topic archived. No new replies allowed.