c++ - int* 参数是否与 int[] 参数完全相同

标签 c++ c function pointers parameters

下面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/

相关文章:

c - 返回一个偶数递归

c++ - 试图引用已删除的函数

c++ - 折叠逗号如何工作?

c++ - Debian Buster中的库不匹配?

c - 使用 UNIX 管道进行进程同步-饥饿

c - 有没有C的子集可以这样写: i=+1?

c++ - 将约束应用于模板的三种方式有什么区别?

c++ - 这会彻底清除类对象动态分配的结果吗?

javascript - 将数组从函数中推送到另一个函数中

postgresql - 在 PostgreSQL 查询中返回超过 24 小时