1

the code below changes the values of arr in function check and prints out values of "2", even though I didn't pass the array in check function in a pointer. How is that possible?

 #include <stdio.h>
 #include <stdlib.h>
 void check(int n,int array[]);

 int main()
 {
     int arr[]={1,2,3,4};
     int i;
     check(4,arr);

     for(i=0;i<4;i++){
         printf("%d\n",arr[i]);
     }
     return 0;
 }

 void check(int n,int array[])
 {
     int j=0;

     while(j<n){
         array[j]=2;
         j++;
     }
 }
Prof. Falken
  • 22,327
  • 18
  • 94
  • 163

2 Answers2

9

Keep in mind that

void check(int n,int array[]);

is the same as

void check(int n,int *array);

and so, when you use

check(4,arr);

you are actually doing

check(4,&arr[0]); /* This is called array "decay" */

and because array decays to a pointer which points to the address of its first element. So, it means that the "array" is passed by reference.

Community
  • 1
  • 1
Spikatrix
  • 19,378
  • 7
  • 34
  • 77
  • thank you! I have another inquiry! When I create a pointer with a zero value in check function and assign it's adress to each of array elements, the arr prints it's original values not zeros. any explanations? – Belal Fathy Sep 10 '15 at 11:40
  • 1
    @BelalFathy I did not understand. Could you show some code? – Spikatrix Sep 10 '15 at 11:44
4

In C, arrays are converted ("decaying") automatically to pointers when sent to functions.

Prof. Falken
  • 22,327
  • 18
  • 94
  • 163