我的团队(包括我自己)是C++新手。我们的新开发项目中有一个需要与接受数组输入的C函数进行接口交互的C++函数。为了实现这一点,类似以下结构的内容被创建:
#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;
}
编译后,这将按预期工作:它会打印出数组的内容。
0: 3
1: 4
2: 5
3: 6
但我觉得这样做几乎不合法,或者至少是应该被反对的事情。
这是合法的C++代码吗?也就是说,指向数组引用的指针是否保证指向原始数组?
为什么要像这样使用它,而不是直接使用指针而不是中间使用引用呢?
&some_ref
,其中some_ref
是一个引用,会创建一个指向引用所指向的任何内容的指针。 - user2357112the_c_function
,而不必经过the_cpp_wrapper
。 - user2357112template <std::size_t N> void the_cpp_wrapper(double (&arr)[N]) { the_c_function(arr, N); }
的东西。 - NathanOliverdref
不是对数组的引用,而是对double
的引用。&dref
是该double
的位置。如果所引用的double
恰好是数组的第一个元素,则&dref
当然是该数组第一个元素的位置。(正如已经注意到的那样,这整个过程是完全不必要的 - 只需执行the_c_function(dbl_array, LEN)
即可。) - molbdnilo