简体   繁体   中英

How to pass array element by reference in c++?

Is it possible to pass a single array element by reference (so that the argument passed in is modified)? For example, say this is a main part:

int ar[5] = {1,2,3,4,5};
test(&ar[2]);

And now this is the function definition:

void test(int &p)
{
    p = p + 10;
    return;
}

The above code results in a compilation error.

&ar[2] takes the address of the element at the 3rd position in the array. So you try to pass an int* to an function expecting an int& . Typically you don't need to do anything to an expression to make it be treated as a reference, since a reference is just another name for some object that exists elsewhere. (This causes the confusion, since it sometimes seems to behave like a pointer).

Just pass ar[2] , the object itself:

test(ar[2]);

Maybe it will be clearer if you put the array to one side for a moment, and just use an int .

void test (int &p);
// ...
int a = 54321;
test(a); // just pass a, not a pointer to a

Just to provide an alternative to BobTFish's answer. In case you need to pass an address, then your function definition needs to accept a pointer as an argument.

void test(int *arg);
// ...
int arg = 1234;
test(&arg);

and to use the address of an array element you do the following:

void test(int *arg);
// ...
int arg[0] = 1234;
test(&arg[0]);

Some people add parenthesis to the array element: &(arg[0]) , which is fine when in doubt, But the [] operator has higher precedence than the & operator.

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