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;
}
int arr[]is nothing but an "alternative" writing forint* arr. (And that's why you can seeint main(int argc, char* argv[])orint main(int argc, char** argv).) Even if you were to put a number inside the brackets!: invoid f(int a[10])the10is completely ignored, which meansvoid f(int a[]), i.e.void f(int* a).myFunction(array, 3);your array is implicitly converted to a pointer to its first element, and that pointer is passed to the function (with either writing of the parameter), as if you had calledmyFunction(&(array[0]), 3);. One way to really pass the array (actually, a reference to it) is to write a function liketemplate<size_t size> void g(int (&arr)[size]), which lets you call it this way:g(array);.