下面2个函数本质上是同一个函数吗?
即 int*
是否与 int[]
完全相同?
int myFunction(int* xVals, int* yVals, int nVertices);
int myFunction(int xVals[], int yVals[], int nVertices);
如何使用第一个功能?即,如何在参数中传递数组?以下是否有效/正确?
int xVals[5], yVals[5], zVals[5];
myFunction(xVals, yVals, zVals, 5);
// or should it be..
myFunction(&xVals[0], &yVals[0], &zVals[0], 5);
最佳答案
在函数参数列表中,函数声明是等价的:
int myFunction(int* xVals, int* yVals, int nVertices); int myFunction(int xVals[], int yVals[], int nVertices);
但是,这并不容易概括。在一个函数内部,有很大的区别:
int AnotherFunction(void)
{
int array[] = { 0, 1, 2, 3 };
int *iptr = &array[0];
...
}
而在函数接口(interface)中,这两种参数类型有很大的区别:
int arrays_vs_pointers(int **iptrptr, int array[][12]);
您还询问(更正):
int xVals[5], yVals[5]; myFunction(xVals, yVals, 5); // or should it be.. myFunction(&xVals[0], &yVals[0], 5);
这些调用都是有效的并且彼此等价。
您最初的标题问题“int *
是否与 int []
完全相同?”的答案是 没有。
在非常有限的情况下它们是等价的,但在更多情况下它们是非常不同的。
修改后的标题问题“int *
参数是否与 int []
参数完全相同?”的答案是 < strong>是!
关于c++ - int* 参数是否与 int[] 参数完全相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12558768/