0

While I was learning C++, I came across this piece of code:

int &get(int *arry, int index) { return arry[index]; }
int main() {
    int ia[10];
    for (int i = 0; i != 10; ++i)
        get(ia, i) = i;

My question is, how does it work?

How is this possible since arry is a pointer?

8
  • 2
    Do you have a good C++ book ? Commented Jul 1, 2015 at 15:31
  • @PaulR I am reading C++ Primer 5th Edition Commented Jul 1, 2015 at 15:31
  • The Prata books have always been excellent IMHO. Commented Jul 1, 2015 at 15:31
  • 1
    OK - read up on pointers and references and try and understand the differences. Commented Jul 1, 2015 at 15:32
  • 1
    operator[] dereferences the pointer. Basically treats it as *(arry+index) Commented Jul 1, 2015 at 15:32

3 Answers 3

3

The built-in [] syntax, in fact, works only on pointers. When you use it on an array, the array is first decayed into a pointer to its first element, which is then indexed.

In your example, the array is decayed when you pass it as argument to the function. There is no array reference here.

Sign up to request clarification or add additional context in comments.

Comments

0

In C++, you can think of an array--in this situation--as a pointer to the first item in that array, where all of the items in the array are lined up one after the other in memory:

 _____
|  6  |   <-- ai
|  9  |
|  4  |
|__2__|

So then, *ai should yield 6.

*(ai+1) should be 9 and so on...(as it turns out, ai[x] is syntactic sugar for--it is directly converted to-- *(ai+x))

When you pass in the array, you're only passing a pointer to the first item. The function then returns the value of arry[index] by reference. This means that if we change the return value, we are actually changing arry[index], which we know to be ia[i].

Does this make sense?

Comments

0

Let the base address of an array a[10] be 1000. So, if you want to access the element in index 2 of the array a, you write a[2]. The interpretation of this statement according to the compiler is:

a[2]= 1000 + (2 * 2) = 1004

Thus you access any element by the formula :

a[index]= base_address + (sizeof datatype * index no)

Now, coming to your question, when you give only the name of the array as in ai in your case, you are actually passing the base address of the array. This is the reason you are using the pointer sign in the function parameter.int *arry, int index.

You must be knowing the following :

int a,*b,c;
a=8;
b=&a;
c=*b;

When you print c, you will get 8.

Hence, if index is 2, the line arry[index] is interpreted as :

(base_address) + (sizeof int * 2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.