简体   繁体   English

将数组作为指针传递给函数

[英]Passing an array to a function as a pointer

While I was learning C++, I came across this piece of code: 在学习C ++时,我遇到了这段代码:

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? 由于arry是指针,这怎么可能?

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: 在C ++中,您可以将数组( 在这种情况下)视为指向该数组中第一个项目的指针,其中数组中的所有项目在内存中一个接一个地排列:

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

So then, *ai should yield 6 . 因此, *ai应该产生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) ) *(ai+1)应该为9 ,依此类推...(事实证明, ai[x]是-的语法糖 ,它直接转换为- *(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 . 然后,该函数通过reference返回arry[index]的值。 This means that if we change the return value, we are actually changing arry[index] , which we know to be ia[i] . 这意味着,如果我们更改返回值,则实际上是在更改arry[index] ,我们知道它是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]. 令数组a [10]的基地址为1000。因此,如果要访问数组a的索引2中的元素,则编写a [2]。 The interpretation of this statement according to the compiler is: 根据编译器,此语句的解释为:

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

Thus you access any element by the formula : 因此,您可以通过公式访问任何元素:

a[index]= base_address + (sizeof datatype * index no) a [index] = base_address +(sizeof数据类型*索引号)

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. 现在,来到你的问题,当你给数组的唯一名称,如ai ,你的情况,你实际上是通过数组的基址。 This is the reason you are using the pointer sign in the function parameter. 这就是在函数参数中使用指针符号的原因。 int *arry, int index . 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. 当您打印c时,将得到8。

Hence, if index is 2, the line arry[index] is interpreted as : 因此,如果index为2,则arry[index]行将解释为:

(base_address) + (sizeof int * 2) (base_address)+(sizeof int * 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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