简体   繁体   中英

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". Where is the difference?

int array[]:

void myFunction(int arr[], int size) {

    for (int i = 0; i < size; ++i)
        arr[i] = 1;
}

int * array:

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 ." This is just a syntactic quirk of C++: the outermost [] in a function parameter of non-reference type is synonymous with * .

表达同一事物的不同方式。您只是通过指针将数组传递给函数。

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. 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 []". The use of pointers of table has an interest only for a dynamic allocation, when the array size is not known on design-time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM