[英]Difference between int * array and int array[] in a function parameter
I have seen that the array values will change if the function parameter is "int arr[]" or "int * arr". 我已经看到,如果函数参数是“int arr []”或“int * arr”,数组值将会改变。 Where is the difference? 区别在哪里?
int array[]: int array []:
void myFunction(int arr[], int size) {
for (int i = 0; i < size; ++i)
arr[i] = 1;
}
int * array: int *数组:
void myFunction(int * arr, int size) {
for (int i = 0; i < size; ++i)
arr[i] = 1;
}
Both functions change the array values. 这两个函数都会更改数组值。
int main(){
int array[3];
array[0] = 0;
array[1] = 0;
array[2] = 0;
myFunction(array, 3);
return 0;
}
There is no difference. 没有区别。 Both functions types (after adjustment) are "function taking a pointer to int
and an int
, returning void
." 两种函数类型(调整后)都是“函数获取指向int
和int
的指针,返回void
。” This is just a syntactic quirk of C++: the outermost []
in a function parameter of non-reference type is synonymous with *
. 这只是C ++的一个语法怪癖:非引用类型的函数参数中的最外层[]
与*
同义。
表达同一事物的不同方式。您只是通过指针将数组传递给函数。
when you pass an array to functions it implicitly passes it by pointer. 当您将数组传递给函数时,它会通过指针隐式传递它。 because if there is many elements in array pass by value copying it is a Huge overhead. 因为如果数组中的许多元素通过值复制传递,那么这是一个巨大的开销。 even-though it looks different its same. 即使它看起来与众不同。
you can't use both functions at same time. 你不能同时使用这两个功能。 if you do its compile time error 如果你做它的编译时错误
error: redefinition of 'void myFunction(int*, int)'
it is already defined.
There are no difference. 没有区别。 In fact, a declaration of an array return allawys a pointer. 事实上,数组的声明返回allawys指针。 Only, when you specify in the declaration that the variable is an array (ie. with []), it is not necessary to specify that it will be a pointer, because this is made implicitly. 只有当你在声明中指定变量是一个数组(即带有[])时,没有必要指定它将是一个指针,因为这是隐式的。 But when you do not specify this, you must declare it as a pointer if you went affect it a table variable, or a result of "new []". 但是当你没有指定它时,如果你影响它是一个表变量,或者是“new []”的结果,你必须将它声明为指针。 The use of pointers of table has an interest only for a dynamic allocation, when the array size is not known on design-time. 当在设计时不知道数组大小时,使用表指针仅对动态分配感兴趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.