The problem i am trying to pass array char arr[6] = {"1","2",etc.}
to a function that takes parameter like this void foo(char* &arr,...)
and it does not work. Can anyone explain it to me please ?
Asked
Active
Viewed 62 times
0

Dang Nguyen
- 61
- 8
-
5Because an array is not a pointer. And a pointer is not an array – StoryTeller - Unslander Monica Sep 12 '17 at 14:56
-
2Those questions are answered [here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282). – nwp Sep 12 '17 at 14:56
-
1Possible duplicate of [Passing an array by reference](https://stackoverflow.com/questions/5724171/passing-an-array-by-reference) – AMA Sep 12 '17 at 14:56
-
3Does `char arr[6] = {"1","2",etc.}` actually compile? – NathanOliver Sep 12 '17 at 14:58
1 Answers
6
char arr[6]
is an array.
char* &arr
is a(n lvalue) reference to a pointer.
Now, since the argument is not of correct type, it has to be converted. An array implicitly decays (decaying is a kind of conversion) into a pointer to first element.
But this decayed pointer is a temporary (an rvalue). Non-const lvalue references can not refer to rvalues, so it would be ill-formed to call foo
with an array argument.
You can create a pointer variable; that can be passed to foo
:
char* ptr = arr;
foo(ptr, ...);
The function may then modify that pointer (i.e. make it point to some other char
object), since the reference is non-const.
PS. There is something very wrong with the initialization of your array. "1"
and "2"
are not char
objects.

eerorika
- 232,697
- 12
- 197
- 326