Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;

 }
share|improve this question
1  
have a look at this stackoverflow.com/questions/5491789/… –  R.S May 25 '13 at 9:29
3  
No difference. At all. In a function parameter list, int arr[] is nothing but an "alternative" writing for int* arr. (And that's why you can see int main(int argc, char* argv[]) or int main(int argc, char** argv).) Even if you were to put a number inside the brackets!: in void f(int a[10]) the 10 is completely ignored, which means void f(int a[]), i.e. void f(int* a). –  gx_ May 25 '13 at 9:54
    
And as said in answers, for the call 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 called myFunction(&(array[0]), 3);. One way to really pass the array (actually, a reference to it) is to write a function like template<size_t size> void g(int (&arr)[size]), which lets you call it this way: g(array);. –  gx_ May 25 '13 at 10:08
add comment

4 Answers

There is no difference. Both functions types (after adjustment) are "function taking a pointer to int and an int, returning void." This is called arrays "decaying" to pointers.

share|improve this answer
add comment

Different ways to express the same thing.You are simply passing an array to functions by pointer.

share|improve this answer
add comment

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.
share|improve this answer
    
I know, I know, it was just to set an example ^^. –  user2273681 May 25 '13 at 9:33
add comment

Arrays in c++ are passed by reference to the functions ,so they will change outside the function if you change them in the function which they are passed to.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.