简体   繁体   中英

Passing an array to a function as a pointer

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?

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.

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM