您需要确切地知道调用的 C++ 函数期待什么。
在 C(和 C++)中,所有这些函数签名的所有意图和目的都完全相同:
void foo( float *x , float *y ) ;
void foo( float *x , float y[] ) ;
void foo( float x[] , float *y ) ;
void foo( float x[] , float y[] ) ;
它们都带有 2 个参数,每个参数都包含一个指向(包含地址)float 类型变量的指针。所有这些表达式在 C/C++ 中都是完全相同的:
float x[] ;
float *y ;
float r1 = *(x+37) ; // all evaluate to the zero-relative
float r2 = x[37] ; // 37th element of the array.
float r3 = *(y+37) ;
float r4 = y[37] ;
- 表达式
*x 表示,“获取位于x 中包含的地址的float(4 个字节)。
- 表达式
*(x+n),其中n 是一个整数值,它表示“取x 中包含的地址,并将通过表达式sizeof(float) * n 获得的字节偏移量相加。获取找到的float 值在结果地址。
- 数组表达式
x[n] 完全等价于指针表达式*(x+n)。
由于 C/C++ 中的数组没有任何关联的元数据来描述它们的大小,因此您需要确切地知道被调用函数的期望。
通常,传递一个指针(通过引用调用)以允许调用者取消引用该点并为您设置一个值 - 相当于 C# 的 ref 和 out 关键字:
float x ;
float y ;
Foo( ref x , ref y ) ; // the callee MAY, but is not REQUIRED to set a value before returning to the caller.
Bar( out x , out y ) ; // the callee MUST set a value before returning to the caller.
您的函数使用的惯用语总是用于定位数组,但通常也会传递一个大小:
void foo( float *array , int array_length ) ;
虽然这并不罕见,但如果函数期望数组是一个非零数值列表,则类似于 C 风格、以 NUL 结尾的字符串。给定函数签名,例如:
float compute_mean( float *Xs ) ;
这样调用它并不罕见:
float Xs[] = { 3.0 , 2.5 , 9.8 , 7,5 , 0 , } ;
float mean = compute_mean( Xs ) ;
定义如下:
float compute_mean( float *Xs )
{
float n = 0.0 ;
float sum = 0.0 ;
float mean ;
while ( *p )
{
++n ;
sum += *p++ ;
}
mean = n > 0 ? sum / n : 0.0 ;
return mean ;
}
所以你需要知道你正在调用的方法的语义。
希望这会有所帮助。