5

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.

1
  • 2
    You should include the errors you are receiving. Commented Jan 26, 2016 at 9:09

2 Answers 2

15

&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
Sign up to request clarification or add additional context in comments.

Comments

3

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.

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.