My team (including myself) is new to C++. A piece of our new development is a C++ function that needs to interface with a C function that takes an array as input. Something like the following construct was made to achieve this:
#include "stdio.h"
void the_c_function(double *array, int len)
{
for (int i = 0; i < len; i++)
{
printf("%d: %g\n", i, array[i]);
}
}
void the_cpp_wrapper(double& dref, int len)
{
the_c_function(&dref, len);
}
int main()
{
const int LEN = 4;
double dbl_array[LEN] = { 3,4,5,6 };
the_cpp_wrapper(dbl_array[0], LEN);
return 0;
}
When compiled, this works as expected: it prints the contents of the array:
0: 3
1: 4
2: 5
3: 6
But this feels hardly legal to me or at the best something that should be discouraged.
Is this legal C++, i.e. is it guaranteed that a pointer to a reference of an array points to the original array?
Is there any reason why one would do it like this instead of using a pointer directly instead of using the reference as inbetween?
The question of code readability aside,
is it guaranteed that a pointer to a reference of an array points to the original array?
Yes, see § 5.5 Expressions:
If an expression initially has the type “reference to
T
” ([dcl.ref], [dcl.init.ref]), the type is adjusted toT
prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.
And §8.3.2 References:
4 It is unspecified whether or not a reference requires storage.
5 There shall be no references to references, no arrays of references, and no pointers to references.
In other words, an "address of a reference" isn't a thing; given double& dref
, taking an address &dref
will give the address of the original element inside the array.